0
#include<iostream>
using namespace std;

class A
{
public:
   A() { cout << "A Creator" << endl; }
   ~A() { cout << "A Destroyer" << endl; }
};

class B : public A
{
public:
    B() { cout << "B Creator" << endl; }
    virtual ~B() { cout << "B Destroyer" << endl; }
};

void main()
{
    A* temp = new B;
    delete temp;
}

Error screenshot

I'm not sure I think this is what I think. I am definitely wondering why the error is happening.

temp allocates a derived class B and stores it in a pointer type (base class A).

At this time, the compiler is based on the pointer data type.

The virtual function table is not created because the base class destructor does not have a virtual declaration.

Class B creates a virtual function table. A virtual function table pointer is also created.

When trying to destroy temp, temp calls the pointer data type destructor and issues a problem.

 

Class B virtual function table pointer can not be found.

This is because the pointer data type is a non-virtual base class.

Austin Brunkhorst
  • 20,704
  • 6
  • 47
  • 61
  • 4
    `A` should have a `virtual` destructor, but doesn't. – nwp Jan 29 '18 at 23:30
  • 1
    You need to declare `~A()` virtual (and once you do, the `virtual` on `~B()` is harmless but unnecessary). As-is, your `delete temp;` gives undefined behavior. – Jerry Coffin Jan 29 '18 at 23:30
  • Also forget about virtual function tables. There is no such thing in the standard. Whenever a function is called that happens to be `virtual` then the most derived overriding function is called. That's all there is to it. – nwp Jan 29 '18 at 23:31
  • Your C++ book should explain virtual destructor and inheritance. –  Jan 29 '18 at 23:33
  • Possible duplicate of [When to use virtual destructors?](https://stackoverflow.com/questions/461203/when-to-use-virtual-destructors) –  Jan 30 '18 at 00:35

2 Answers2

6

Your code invokes undefined behavior. Excerpt from the "Effective C++" book by Scott Meyers explains why:

When derived class object is deleted through a pointer to a base class with a non-virtual destructor, results are undefined.

Your base class A should have a virtual destructor:

virtual ~A() { std::cout << "A Destroyer" << '\n'; }

If classes are meant to be used in polymorphic ways then the base class should have the virtual destructor.

Ron
  • 14,674
  • 4
  • 34
  • 47
2

delete on a pointer whose pointed type does not have a virtual destructor has undefined behviour if the pointer points to a base sub-object. temp points to the base sub-obect of a B instance and A::~A is non-virtual.

To fix, declare A::~A virtual.

eerorika
  • 232,697
  • 12
  • 197
  • 326