Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ destructors question

Tags:

c++

destructor

With regards to the sample code below, why is the destructor for the base class called twice?

class Base {
public:
    Base() {
        std::cout << "Base::Base()" << std::endl;
    }

    ~Base() {
        std::cout << "Base::~Base()" << std::endl;
    }
};

class Derived : public Base {
public:
    Derived() {
        std::cout << "Derived::Derived()" << std::endl;
    }

    ~Derived() {
        std::cout << "Derived::~Derived()" << std::endl;
    }
};

int main() {
    Base a = Derived();
    return EXIT_SUCCESS;
}

Here is a sample of the output when the program is run:

Base::Base()
Derived::Derived()
Derived::~Derived()
Base::~Base()
Base::~Base()
like image 786
Harish H Avatar asked Nov 27 '22 10:11

Harish H


1 Answers

What happens is called slicing. You initialize an object of type Base with an object of type Derived. Since any object of type Derived has also an object of type Base contained (called "base-class sub-object"), there will be two Base objects and one Derived object in existance throughout the program. The Derived object (and its base-class sub-object of type Base) only exists for the time of initialization, while the remaining Base object exists until end of main.

Since there are two Base objects and one Derived object, you will also see one more Base destructors run.

like image 88
Johannes Schaub - litb Avatar answered Dec 09 '22 06:12

Johannes Schaub - litb