RenanJosé
RenanJosé

Reputation: 93

Is the class destructor called in an assignment?

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?

Upvotes: 9

Views: 4845

Answers (5)

marc_s
marc_s

Reputation: 455

car1 = car2;

this causes the destructer of car1 NOT to be executed.
if you want the destructor to be called, car1 needs to be called Explicitly or it should go out of scope.(as our Friend Baum mit Augen said, calling car1 Explicitly is rarely in need).

Upvotes: 0

Baum mit Augen
Baum mit Augen

Reputation: 50053

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.

Upvotes: 5

Serge Rogatch
Serge Rogatch

Reputation: 15030

You can see in the following program that the destructor does not get called for t1 or t2 till the end of main() function:

#include <iostream>
#include <string>

class Test
{
    std::string _name;
public:
    Test(std::string name) : _name(name) { }
    ~Test()
    {
        std::cout << "Destructor " << _name << std::endl;
    }
    Test& operator=(const Test& fellow)
    {
        // avoid changing the name of the object
        std::cout << "Assignment operator " 
            << _name << "=" << fellow._name << std::endl;
        return *this;
    }
};

int main()
{
    Test t1("t1"), t2("t2");
    t1 = t2;
    return 0;
}

In an assignment t1=t2, just the assignment operator is called on t1 taking t2 as a parameter. If you need to release the resources of t1, you can do that in the assignment operator implemented as the code example shows. Don't forget to implement copy constructor too - that's for the cases of assignment to uninitialized instance (no need to release previously held resources because there are no resources held by the time of copy constructor call).

Upvotes: 3

kiviak
kiviak

Reputation: 1103

Car car1();//error, Car car1; call default construct function
Car car2(); //error, Car car2;call default construct function

car1 = car2; //call operator=() 

Upvotes: 1

user2946316
user2946316

Reputation:

Well it depends. If you allocate memory on the heap and assign one variable to another it wont call the destructor:

{
    Car* car1 = new Car();
    Car* car2 = new Car();
    car1 = car2;
}

But this will, and its because it goes out of scope not because of the copy assignment.

{
    Car car1;
    Car car2;
    car1 = car2;
}

Upvotes: 0

Related Questions