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 aIt 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
As a general rule in SOPHYA, objects which implements reference sharing on their data members have a copy constructor which shares the data, while the assignment operator copies or duplicate the data.