Copy Constructor vs. overloading = operator

Started by
1 comment, last by Bregma 18 years ago
Does anyone know what the difference between the copy constructor and overloading an = operator is in c++?
n/a
Advertisement
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.
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.

Stephen M. Webb
Professional Free Software Developer

This topic is closed to new replies.

Advertisement