Jump to content
  • Advertisement
Sign in to follow this  

Copy Constructor vs. overloading = operator

This topic is 4489 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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;


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
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!