This Season
 

How to Use C++ Virtual Destructors

A virtual method has no direct implementation and its behavior is determined by the method with the same signature that is on the lowest inheritance level of the instantiated object. A destructor is automatically called when the object is destroyed. A virtual destructor in C++ is used primarily to prevent resource leaks by performing a clean-up of the object. The following steps explain how to use virtual destructors in C++.

Related Searches:
    Difficulty:
    Challenging

    Instructions

      • 1

        Determine when to use a virtual destructor. A destructor for a class should be virtual when an object of a derived class will be destroyed by invoking the base class destructor. The destructor must be virtual when you delete a pointer to an object and it is possible that it points to a derived class.

      • 2

        Learn an important difference between a destructor and other member methods. In both cases, the method of the derived class is invoked if it is implemented. However, the base class destructor is subsequently called whereas this does not happen with other methods.

      • 3

        Consider the following example of a virtual destructor:

        #include
        class Base_class
        {
        public:
        Base_class(){ cout<<"Constructor: Base_class"< // virtual keyword is needed here
        virtual ~ Base_class(){ cout<<"Destructor : Base_class"< };
        class Derived_class: public Base_class
        { public:
        Derived_class(){ cout<<"Constructor: Derived_class"< ~ Derived_class(){ cout<<"Destructor : Derived_class"< };
        void main()
        {
        Base_class *p = new Derived_class();
        delete p;
        }

      • 4

        Observe the use of the virtual keyword in the example in Step 3. If the destructor of the base class were not declared as virtual, the destructor of the derived class would not get called.

      • 5

        Implement at least an empty body for a virtual destructor since a pure virtual function cannot be declared.

    Related Searches

    Resources

    Read Next:

    Comments

    You May Also Like

    Follow eHow

    Related Ads