Saturday, September 10, 2011

Copy constructor and assignment operator


Copy constructor and assignment operator

In C++, objects can be copied by assignment or by initialisation. Copying by initialisation corresponds to creating an object and initialising its value through the copy constructor. The copy constructor has its first argument as a reference, or const reference to the object's class type. It can have more arguments, if default values are provided. Copying by assignment applies to an existing object and is performed through the assignment operator (=). The copy constructor implements this for identical type objects:
class MyObject {
public:
  MyObject();      // Default constructor
  MyObject(MyObject const & a);  // Copy constructor
  MyObject & operator = (MyObject const & a) // Assignment operator
}
The copy constructors play an important role, as they are called when class objects are passed by value, returned by value, or thrown as an exception.
// A function declaration with an argument of type MyObject,
// passed by value, and returning a MyObject
MyObject f(MyObject x) 
{
  MyObject r;
  ...
  return(r);  // Copy constructor is called here
}
// Calling the function :
MyObject a;
f(a);        // Copy constructor called for a
It should be noted that the C++ syntax is ambiguous for the assignment operator. MyObject x; x=y; and MyObject x=y; have different meaning.
MyObject a;        // default constructor call
MyObject b(a);     // copy constructor call
MyObject bb = a;   // identical to bb(a) : copy constructor call
MyObject c;        // default constructor call
c = a;             // assignment operator call

No comments:

Post a Comment