Abrar
Abrar

Reputation: 7232

Destructor execution of object of an inherited class

I have the following sample code of two classes Programmer and CSstudent where

CSstudent:public Programmer

Destructors are defined for both the classes :

class Programmer{
           .........
            public:
               ~Programmer(){
                 cout<<"A Programmer obj destroyed";       
        }
      }

class CSstudent:public Programmer{
           .........
       public:
        ~CSstudent(){
          cout<<"CSstudent obj destroyed";
      }
         }

Now in the main() :

int main(){
    CSstudent cs1;

    /* call to CSstudent member functions by invoking the cs1 object
      ........... */

    cout<<cs1.getName()<<cs1.getUni()<<cs1.getLang()<<endl;
}

After the program runs I get the following: CSstudent obj destroyed A Programmer obj destroyed

I know that destructors are not inherited, and destructors are invoked when objects go out of scope. I initialized a CSstudent object then why do the destructor of the Programmer class invoked ?

I was hoping for this output: CSstudent obj destroyed

Upvotes: 1

Views: 456

Answers (2)

Gacci
Gacci

Reputation: 1398

Because internally when you create a CSstudent object, a Programmer object is created. Thus, when you delete CSstudent the base object must be deleted too.

Upvotes: 0

RyanP
RyanP

Reputation: 1918

A derived class essentially contains the base class within it. When the derived class is constructed, the base class is constructed first and the derived class is constructed next (which makes sense, in case your derived class requires the use of base class variables that it assumes have been properly initialized). The opposite is true on destruction, the derived class destructor is called first, then the base class destructor is called to cleanup base class information.

Upvotes: 5

Related Questions