Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the class destructor called in an assignment?

Tags:

c++

Does the class destructor get called when a variable that already holds an object receives another object in a c++ code?

Car car1;
Car car2;

car1 = car2;

Does the car1 destructor get called in this situation?

like image 774
RenanJosé Avatar asked Jun 28 '15 16:06

RenanJosé


1 Answers

The destructor of car1 will not be executed when you do

car1 = car2;

Only the (probably implicitly generated) Car::operator= (const Car&); will be called on car1.

The destructor will only be called when car1 goes out of scope (or when you call it explicitly, but you really rarely need that).

Also note that car1 does not "hold" a Car instance, it is the instance itself.

like image 60
Baum mit Augen Avatar answered Oct 26 '22 08:10

Baum mit Augen