Constructors and Destructors


  • Again consider the same two classes: counter & countdown. The counter class has got two constructor counter () and counter (int c). The countdown class which has been derived from the counter class has also got two constructor countdown (), countdown (int c). See the following code
    # include < iostream.h >
    class counter
    { protected: unsigned int count; 
    public : counter() { count = 0; }
    counter(int c) { count = c;}
    ……………………………
    };
    class countdown : public counter
    { public: countdown () : counter() { };
    countdown (int c) : counter (c) { };
    ……………………………….
    };
    void main() {
    countdown c1; countdown c2(100);
    cout << "c1 = " << c1 .getcount();
    cout << "c2 ="  << c2.getcount();
    c1--; c1++; c1++;
     c2--; c2--; 
    countdown c3 = c2--;
    cout << "c1 =" << c1 .getcount() << endl; 
    cout << "c2 =" << c2.getcount() << endl; 
    cout << "c3 =" << c3.getcount() << endl;
    }
    

  • In this example you can see that the declaration of a constructor in the derived class is as
  • countdown( ): counter( ) {} and countdown(int x ) counter(x) { }.
  • Actually the derived class constructors call the base class constructors.
  • Any additional statements can be written inside the braces.
  • In this example, the derived class constructors do nothing additional, so there are no statements within the braces.
  • Here, the value of count is passed to the derived class constructor which in turn passes it to the base class constructor which does the actual initialization.
    Click here for constructor example
  • Since a derived class may provide data members on top of those of its base class, the role of the constructor and destructor is to, respectively, initialize and destroy these additional members.
  • When an object of a derived class is created, the base class constructor is applied to it first, followed by the derived class constructor.
  • When the object is destroyed, the destructor of the derived class is applied first, followed by the base class destructor.
  • In other words, constructors are applied in order of derivation and destructors are applied in the reverse order. For example, consider a class C derived from B which is in turn derived from A. Following figure illustrates how an object c of type C is created and destroyed.
  • class A{/*... */};
  • class B: public A{/*…*/}
  • class C: public B (/* .. */}


Inheritance << Previous

Next >> Overriding Member Functions

Our aim is to provide information to the knowledge seekers.


comments powered by Disqus
Footer1