MyClass* x = new C;
MyClass* y = new C;
x = y; // here x.operator= is called
or see example below when pointers are not used
Copy Constructor
Is called in many instances including:
- Pass by value into a method
- Returning by value from a method
Implemented by
MyClass* x = new MyClass;
MyClass* y = new MyClass (x);
Example Code:
#includeusing namespace std; class MyClass { public: MyClass() : value(0) {cout << "default ctr called" << endl;} ~MyClass() {cout << "default dtr called" << endl;} // Copy Constructor MyClass(const MyClass& other) { cout << "copy ctr called" << endl; value = other.value; } // Assignment Operator MyClass& operator= (const MyClass& other) { cout << "assignment operator called" << endl; value = other.value; return *this; } void setValue(const int& newValue) { value = newValue; } int getValue() { return value; } private: int value; }; int main () { MyClass x; MyClass y; x.setValue('x'); y.setValue('y'); cout << "x is now " << x.getValue() << endl; cout << "y is now " << y.getValue() << endl; cout << "calling \'x = y\'" << endl; x = y; // assignment operator cout << "x is now " << x.getValue() << endl; cout << "y is now " << y.getValue() << endl; cout << "calling 'MyClass z = y'" << endl; MyClass z = y; // copy constructor cout << "x is now " << x.getValue() << endl; cout << "z is now " << z.getValue() << endl; } Expected Output: default ctr called default ctr called x is now 120 y is now 121 calling 'x = y' assignment operator called x is now 121 y is now 121 calling 'MyClass z = y' copy ctr called x is now 121 z is now 121 default dtr called default dtr called default dtr called
In summary, if assigning values to an object which already exists, the operator== method is used.
However if assigning values to a new object, the copy constructor is used
No comments:
Post a Comment