C++ self-assignment -If object assigned to itself what happens

Answer: Self assignment of object in C++ is OK only if object declaration and initialization has been already done before. Otherwise, we may get compiler error for object declaration or run time crash, stating object has not been initialized.

In below complete example, in class A, we have declared an object int Id and has initialized it in constructor with value 10.

if we call below statements compiler will flash an error as class object is not initialized yet and we are trying to assign to itself (other object)

A obj(obj);  //Error : obj undeclared identifier

But, If we create an object of a class i.e. A obj; , constructor will be called where int Id has already been initialized like below
Now, if we assign object to itself it will be OK. as int Id declaration and initialization is done.

obj = obj; // self assignment OK

Example for self assignment of object in C++

#include 
using namespace std;

class A{
   int Id;
   public:
   A()
   {
     cout<<"Inside constructor"<<endl;
     Id=10;
   }
   A(const A &a)
   {
    cout<<"Inside copy constructor"<<endl;
    Id=10;
   }
   int GetId()
   {
    return Id;
   }
};

int main(){

//Test object self assignment

// Scenario 1:
//A obj(obj);  //Error : obj undeclared identifier

// Scenario 2:
//Below code is OK.
A obj; //declaration and initialization done here
obj = obj; // self assignment

cout <<"Id is : "<<obj.GetId()<< "\n";

// Scenario 3:

//A *a = new A(*a);// compiled but crashes on run time stating : variable 'a' is being used without being initialized.

// Scenario 4:
//Below code is ok.
A*a = new A(); //declaration and initiazation done here
a = new A(*a); // self assignment. Copy constructor will be called here.
cout <<"Id is : "<<a->GetId()<< "\n";


return 0;
}

Output:

Inside constructor

Id is : 10

Inside constructor

Inside copy constructor

Id is : 10

Related Posts