***Welcome to ashrafedu.blogspot.com * * * This website is maintained by ASHRAF***

Monday, June 14, 2021

Constructors and Destructors in Base and Derived Classes

When the constructors and destructors defined in both base and derived classes, consider the following:

1) If both base and derived class has constructors, the base class constructor is executed first and then the derived class constructor is executed.

2) If the base class constructor does not take any argument, the derived class may not have a constructor.

3) If the base class constructor with one or more arguments, then the derived class must have a constructor function to pass arguments to the base class constructor. It is defined as follows:

public:

Derived_classname(datatype arg1,datatype arg2) : base_classname(arg1)

{

Derived_class_variable = arg2;

}

For a base class constructor, the arguments must be passed by the derived class constructor.

4) The order of execution of destructors is just reverse of constructors, that is, first the destructor of derived class is called then the base class destructor is called.

Example:

#include <iostream.h>

class BaseClass

{

 public:

 BaseClass() // Constructor

 {

cout << "This is the BaseClass constructor.\n";

 }

 ~BaseClass() // Destructor

 {

cout << "This is the BaseClass destructor.\n";

 }

 };

class DerivedClass : public BaseClass

{

 public:

 DerivedClass() // Constructor

 {

cout << "This is the DerivedClass constructor.\n";

}

 ~DerivedClass() // Destructor

 {

 cout << "This is the DerivedClass destructor.\n";

 }

 };

void main()

{

 cout << "We will now define a DerivedClass object.\n";

 DerivedClass object;

 cout << "The program is now going to end.\n";

}

Output:

We will now define a DerivedClass object.

This is the BaseClass constructor.

This is the DerivedClass constructor.

The program is now going to end.

This is the DerivedClass destructor.

This is the BaseClass destructor.

 

//Demonstration on base constructor with argument

#include<iostream.h>

#include<conio.h>

class Base

{

protected:

int a;

public:

Base(int k)

{ a=k; }

};

class Derived : public Base

{

private:

int b;

public:

Derived(int p, int q) : Base(p)

{ b=q; }

void show()

{

cout<<"\nBase class a= "<<a;

cout<<"\nDerived class b= "<<b;

}

};

void main()

{

clrscr();

Derived d(10,5);

d.show();

getch();

}

No comments:

Post a Comment