Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The copy constructor and assignment operator

If I override operator= will the copy constructor automatically use the new operator? Similarly, if I define a copy constructor, will operator= automatically 'inherit' the behavior from the copy constructor?

like image 317
Paul Manta Avatar asked Mar 20 '11 11:03

Paul Manta


People also ask

What is copy constructor and assignment operator?

The Copy constructor and the assignment operators are used to initializing one object to another object. The main difference between them is that the copy constructor creates a separate memory block for the new object. But the assignment operator does not make new memory space.

What is a copy assignment operator?

A copy assignment operator of class T is a non-template non-static member function with the name operator= that takes exactly one parameter of type T, T&, const T&, volatile T&, or const volatile T&. For a type to be CopyAssignable, it must have a public copy assignment operator.

Is copy constructor called on assignment?

A copy constructor is called when a new object is created from an existing object, as a copy of the existing object. The assignment operator is called when an already initialized object is assigned a new value from another existing object.

What is the difference between the copy constructor and the assignment operator ie when will each of these functions be called and why?

The copy constructor initializes the new object with an already existing object. The assignment operator assigns the value of one object to another object both of which are already in existence.


1 Answers

No, they are different operators.

The copy constructor is for creating a new object. It copies an existing object to a newly constructed object.The copy constructor is used to initialize a new instance from an old instance. It is not necessarily called when passing variables by value into functions or as return values out of functions.

The assignment operator is to deal with an already existing object. The assignment operator is used to change an existing instance to have the same values as the rvalue, which means that the instance has to be destroyed and re-initialized if it has internal dynamic memory.

Useful link :

  • Copy Constructors, Assignment Operators, and More
  • Copy constructor and = operator overload in C++: is a common function possible?
like image 139
Saurabh Gokhale Avatar answered Sep 21 '22 12:09

Saurabh Gokhale