constructor and destructor function with derived


Constructor and Destructor function with derived classes

If there are constructors included in the base class and the derived class, the compiler automatically calls both of them. This occurs because as soon as the derived class constructor gets control and establishes formal arguments, the base class constructor will be called instantaneously, i.e., before the derived class initialization list is honored.

Syntax in the derived class base/members initialization list :

  • The base class name ( name of base constructor )
  • A list of arguments among parentheses, as in any normal function call. To explicitly invoke the base class default constructor , leave the argument list empty.

Remember the base class constructor always is called first.

                class base

                 {

                  public :

base(int n=0);

 ~base();

int get_base_number();

                  protected:

                int base_number;

                 };

base::base(int n=0)

 {

base_number = n;

cout << "base constructor ";

 }

base::~base()

 {

cout << "base destructor ";

 }

int base::get_base_number()

 {

return base_number;

      }

 

                class derived : public base

                 {

                  public :

derived(int b=0, int d =0): base(b),derived_number(d);

~ derived();

int get_derived_number();

                   private :

 int derived_number;

                  };

 

derived::derived(int b=0, int d =0): base(b),derived_number(d)

  {

                                cout << " derived constructor ";

  }

 

derived::~ derived()

                 {

                     cout << "derived destructor ";

                 }

int derived::get_derived_number()

 {

return derived_number;

 }

void main()

 {

  derived d(1,2);

 

cout < " d= " << d.get_base_number()<<",";

cout << d.get_derived_number();          

 }

 

 

Output:

 

                                Base constructor

                                Derived constructor

                                D = 1,2

                                Derived  destructor

                                Base destructor

 

Request for Solution File

Ask an Expert for Answer!!
C/C++ Programming: constructor and destructor function with derived
Reference No:- TGS0309445

Expected delivery within 24 Hours