Virtual Destructors In C++

Virtual Destructors In C++

                            Base class destructor should always be virtual.The reason is if you want to delete the object of derived class it will not deleted.Lets take an example:

Forexample

        class A{
                    public: 
                    ~A(){
                            cout<<"Base Class"<<endl; 
                            }
                      };

        class B :public A{
                    public: 
                    ~B(){
                            cout<<"Derived Class"<<endl; 
                            }
                       };

        int main(){
                        A *ptr=new B;
                        delete ptr;
                        return 0;
                        }

Output
                    Base Class

                        From above the example you can see that the base class destructor is not virtual and derived class destructor is not called.
                                                So the solution for this is to put virtual before the base class destructor.Just add virtual keyword like that:

                    virtual ~A(){
                            cout<<"Base Class"<<endl; 
                            }
                      };

                                                   So the output now will be 

Derived Class          
Base Class

Comments

Popular posts from this blog

Friend Function in C++

Data Member and Static Keyword in C++

Use Of CPP