Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ is Virtual destructor still needed if there are no data members in derived?

Suppose I have this code

class Base{
  public:
        int getVal();
  private:
         int a, b;
};

class Derived::public Base{
    public:
         void printVal();
};

int main(){
    Base *b = new Derived();
    delete b;    
}

I know a virtual destructor would delete things properly, but is it bad to delete with base pointer (when there is no virtual destructor) even if there are no virtual functions and no data members in the derived class? What will happen if this is done?

like image 538
snk Avatar asked Oct 15 '10 18:10

snk


People also ask

Do derived classes need a virtual destructor?

Note: in a derived class, if your base class has a virtual destructor, your own destructor is automatically virtual. You might need an explicitly defined destructor for other reasons, but there's no need to redeclare a destructor simply to make sure it is virtual.

When would you not use a virtual destructor?

In short you should not have a virtual destructor if: 1. You don't have any virtual functions. 2. Do not derive from the class (mark it final in C++11, that way the compiler will tell if you try to derive from it).

Does a derived class need a destructor?

No. You never need to explicitly call a destructor (except with placement new). A derived class's destructor (whether or not you explicitly define one) automagically invokes the destructors for base class subobjects. Base classes are destructed after member objects.

Why are virtual destructor needed?

Virtual destructors in C++ are used to avoid memory leaks especially when your class contains unmanaged code, i.e., contains pointers or object handles to files, databases or other external objects.


1 Answers

Is it bad to delete with base pointer (when there is no virtual destructor) even if there are no virtual functions and no data members in the derived class?

Yes.

The behavior is undefined regardless the contents of the derived class.

What will happen if this is done?

Anything could happen.

like image 190
James McNellis Avatar answered Sep 17 '22 13:09

James McNellis