Assignment Operator is used to copy values of one object to another existing object of the same class. The pre requisite for assignment operator to be called is the LHS of the assignment must already be allocated.
In the above sample the third statement uses the = operator but the overloaded assignment operator function is not called as the object "obj3" doesn't exist, hence the copy constructor is called. The copy constructor creates a new object and then copies the value of the source object to the newly allocated object.
The purpose of the copy constructor and the assignment operator are almost equivalent — both copy one object to another. However, the assignment operator copies to existing objects, and the copy constructor copies to newly created objects.
There are three general cases where a copy constructor is called instead of an assignment operator
i) When instantiating one object and initializing it with values from another object.
ii)When passing an object by value.
iii) When an object is returned from a function by value
template <class T> class SampleClass { T var1; public: SampleClass() { }//default constructor SampleClass(T value): var1(value){}//constructor ~SampleClass() {} //destructor SampleClass& operator= (SampleClass &sorce){ //Assignment operator oveloaded if(this = &source){ //Self assign Should not happen - will land up in deep shit
if deep copying is implemted. //however the example takes up shallow copying as member
attributes are all static. }else{ var1 = source.var1; } return *this; } } SampleClass<int> obj1; //calls defaut copy constructor SampleClass<int> obj2(5);//calls constructor SampleClass<int> obj3 = obj2; //calls copy constructor obj1 = obj3; //calls the overloaded assignment operator.
In the above sample the third statement uses the = operator but the overloaded assignment operator function is not called as the object "obj3" doesn't exist, hence the copy constructor is called. The copy constructor creates a new object and then copies the value of the source object to the newly allocated object.
The purpose of the copy constructor and the assignment operator are almost equivalent — both copy one object to another. However, the assignment operator copies to existing objects, and the copy constructor copies to newly created objects.
There are three general cases where a copy constructor is called instead of an assignment operator
i) When instantiating one object and initializing it with values from another object.
ii)When passing an object by value.
iii) When an object is returned from a function by value
No comments:
Post a Comment