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

(Last Updated On: June 3, 2016)

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)

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++


Inside constructor

Id is : 10

Inside constructor

Inside copy constructor

Id is : 10