Skip to main content
gamedev.net
🔒 Locked

Copy Constructor vs. overloading = operator

Started by MasterDario 1 reply 650+ views
Original Post
MasterDario
MasterDario
Does anyone know what the difference between the copy constructor and overloading an = operator is in c++?
n/a
Andorien
Andorien
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.
Bregma
Bregma
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

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.