Question:
In C++ is writing a copy constructor the same as overloading the assignment operator?
1970-01-01 00:00:00 UTC
In C++ is writing a copy constructor the same as overloading the assignment operator?
Three answers:
nightS
2007-07-25 08:58:41 UTC
It will call the copy constructor but there's a different between both..copy constructor (or any other type of constructors) is called ONLY when you INITIALIZE a new instance of a certain class (statically or dynamically)..

so in your example, you used the assignment operator and the copy constructor was called because y1 was being initialized in that statement (X y1)

But, later on in the program...if you needed to write this:

y2=y1;

you will need the assignment operator overloading...and the copy constructor won't be called (No declaration/initialization here)
reach2aish
2007-07-25 07:36:56 UTC
assignment is different from the construction of an object. Copy constructor is called when an object is being defined and is being initialized with a value. Assignment operator is called when a value is assigned to an already defined object.



Note the difference between INITIALIZATION and ASSIGNMENT.



Thus,

X y2;

X y1 = y2;

will call the copy constructor and not the assignment operator.
Mantis
2007-07-25 12:55:10 UTC
They are closely related. When you write one, you should write the other.



The other answerers are correct. The copy constructor is used when you write code like the following:



MyClass X = Y; //invokes copy constructor

MyClass X(Y); //also invokes copy constructor



whereas the operator = is called when you write code like the following:



MyClass X: //invokes default constructor

X = Y; //invokes operator =



Since you rarely see code like "MyClass X = Y", you might be tempted to skimp on the copy constructor. Don't. There's another sneaky place you often find copy constructors: passing variables by value. The standard template library does this ALL THE TIME, so if you have vectors or lists in your code, be aware of this.



MyClass Y; //invokes default constructor

DoSomething(Y); //calls copy constructor



std::vector myVector;



// (pretend we added a bunch of items to vector here)



myVector.push_back(Y); //invokes copy constructor. May also invoke copy constructor on other items already added if vector resizes.



std::sort(myVector); //invokes operator= on any items that move



From the programmer's standpoint, one key thing to remember is that when you write the operator =, you MUST clean up anything you're pointing at already. For example, if you have a pointer in your class, you should free that pointer before copying the value from the right-hand side. Copy constructors tend to be faster than operator= for this reason.



Hope this helps.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...