Sign in to follow this  
MasterDario

Copy Constructor vs. overloading = operator

Recommended Posts

Quote:
Original post by MasterDario
Does anyone know what the difference between the copy constructor and overloading an = operator is in c++?


Operator= is used for assignment after the object has already been created. Like the following:

Object ImaObject;
ImaObject = NoYoureNot;


The copy constructor is called whenever an object is created as a copy of another object. For for instance:

Object ImaObject = Whee;


or

Object ImaObject(Whee);


It's also called whenever you pass it by value to a function.

Share this post


Link to post
Share on other sites
Yes. They're two different things.

A copy constructor created a new object by copying an existing object.

The assignment operator makes one existing object equvalent to another existing object.

Sometimes one can be implemented in terms of the other. For example,

Object& Object::operator=(const Object& rhs)
{
Object tmp(rhs); // use copy ctor to create temp
swap(tmp, *this); // use non-throwing swap to trade contents
} // tmp goes out of scope, frees previous contents of this.

You can also be confused by the occasional assignment syntax of a copy constructor.

Object object1 = object2;

is in fact a copy construction, not an assignment expression.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this