Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Definition of base class destructor not needed?

Tags:

c++

In all the examples I have seen about polymorphism the destructor of the base class is virtual and it is defined with an empty body.

I am trying to get my head around this: why does it have to be an empty body? Why doesn't it work if the method is just declared as virtual but not defined with an emtpy body? Wouldn't it be implemented then by the default destructor? Or the fact that it's being declared as virtual supresses even the default definition and forces to explicitly define the body?

This is what I mean:

class A {
public:
    virtual void f();
    virtual ~A() {}
}

class B : public A {
public:
    ~B() {
        // destroy whatever
    }
}

Why can't ~A() be declared just like this virtual ~A(); without definition?

Also, why does it have to be defined like that (with the empty body) in abstract classes? I have tried to declare the destuctor of an abstract class like this virtual ~A() = 0 and the compiler didn't let me do that.

like image 754
dabadaba Avatar asked Jan 11 '23 09:01

dabadaba


2 Answers

Why can't ~A() be declared just like this virtual ~A(); without definition?

Because a function that isn't defined can't be called. Simple as that. If you don't declare the destructor, the compiler implicitly defines one. But if you provide a declaration yourself then the compiler no longer provides a definition. You can explicitly give it the default definition in C++11 though.

virtual ~A() = default;

Also, why does it have to be defined like that (with the empty body) in abstract classes? I have tried to declare the destuctor of an abstract class like this virtual ~A() = 0 and the compiler didn't let me do that.

Same reason. As long as a destructor is called, it needs to have a definition, just like any other function. Normally a pure virtual function is never called, but destructors are an exception. You will have to provide a definition.

class A {
// ...
    virtual ~A() = 0; // declare destructor as pure virtual
};
// ...
A::~A() {} // define destructor
like image 187
Brian Bi Avatar answered Jan 12 '23 23:01

Brian Bi


The destructor must have a body because it is called when the object is destroyed. Every time a derived object is destroyed, the last step is to call the base class's destructor. Without a body, the linker cannot find a definition of that destructor and the call fails, just like with normal functions not having definitions.

It's entirely possible (and necessary barring some obscure usage) to give a pure virtual destructor a body:

class Foo {
public:
    virtual ~Foo() = 0;
};

Foo::~Foo() {} //pre-C++11
Foo::~Foo() = default; //for an empty body with some benefits; C++11 and on
like image 24
ghostofstandardspast Avatar answered Jan 12 '23 21:01

ghostofstandardspast