keyboardNoob
keyboardNoob

Reputation: 91

Destructor called two times in C++

I have a code with two classes like this:

Class A:

class A {
    int a, b;
public:
    A(int x, int y) {
        a = x;
        b = y;
    }
    ~A() {
        cout << "Exit from A\n";
    }
    void values() {
        cout << a << "\n" << b << endl;
    }
};

Class B:

class B :public A
{
    int c;
public:
    B(int x, int y, int z) :A(x, y)
    {
        c = z;
    }
    ~B() {
        cout << "Exit from B\n";
    }
    void values() {
        A::values();
        cout << c << endl;
    }
};

And main function:

int main()
{
    A testA(1, 2);
    testA.values();
    B testB(10, 20, 30);
    testB.values();
}

That's what i got:

1
2
10
20
30
Exit from B
Exit from A
Exit from A

First is called destructor from class B, then from A twice. Why two times? I don't know how to change it.

Upvotes: 1

Views: 535

Answers (2)

Caleth
Caleth

Reputation: 62531

There are 2 A objects created in main, testA, and the A base-subobject of testB. Both are destroyed at the end of main, in reverse order of how they are declared.

class A {
    int a, b;
    std::string msg;
protected:
    A(int x, int y, std::string m) : a(x), b(y), msg(m) {}
public:
    A(int x, int y) : A(x, y, "Exit from A\n") {}
    virtual ~A() {
        std::cout << msg;
    }
    virtual void values() {
        std::cout << a << "\n" << b << std::endl;
    }
};

class B :public A
{
    int c;
public:
    B(int x, int y, int z) : A(x, y, "Exit from B\n"), c(z) {}
    void values() override {
        A::values();
        std::cout << c << std::endl;
    }
};

Upvotes: 3

Devolus
Devolus

Reputation: 22074

You have Object testA which will call it's destructor from A (1). You have Object testB which is derived from A so it will call destructor B (1) and destructor A (2).

This is exactly what your output says.

Upvotes: 0

Related Questions