1
using namespace std;

class A {};

class B {};

class C : public A {
    public:
    C(){ b = new B();}
    B* b;
    ~C(){
        printf("in destructor\n");
        delete b;
    }
};

void doSomething(A&aref)
{
    C c = (C &) aref;
    c.b = new B();
    int i;
}

int main()
{      
    A * a;

    a = new C();
    printf("Line 1\n");
    doSomething(*a);
    printf("Line 2\n");

    delete(a);

    return 0;
}

Output is:

Line 1
in destructor
Line 2

Tried removing the delete(a) and get same results.

Why don't I see the destructor called twice? I'd expect it to be called at the end of the doSomething function and at the delete call.

Why does the doSomething function call the destructor? And why does the delete(a) not cause an error?

JeJo
  • 30,635
  • 6
  • 49
  • 88
user2706641
  • 67
  • 1
  • 4

1 Answers1

5

You are missing a virtual destructor in A, hence the undefined behavior. Default one for defined behavior.

class A {
public:
    virtual ~A() = default;  
};
JeJo
  • 30,635
  • 6
  • 49
  • 88
  • 2
    That's such a common mistake that I would rather introduce a complier warning of inheriting a class without corral destructor and have a special explicit tag to disable it – Dr Phil May 14 '19 at 23:29