Answer to Question #244140 in C++ for lemhs

Question #244140

What is the purpose of constructors in c++.? How to denote the destructors in c++?

Give the order of execution of the constructors and destructors in a multilevel inheritance. Explain the same with a suitable program .


1
Expert's answer
2021-09-29T18:49:19-0400



Constructor is used for initializing values to the data members of an object. Constructor allocates memory for object.


Destructor is used to destroy object after they go out of scope. Destructors are being denoted by tilde (~).

 Order of execution 

Default constructor of the base class

Default constructor of the derived base

Parameterized constructor of the derived class

Destructors for base class

Destructors for derived class


#include <iostream>
using namespace std;
class Base
{
   int x;


public:
  
   Base()
   {
      cout << "Default Constructor called for the base class\n";
   }
};


class Derived : public Base
{
   int y;


public:
   
   Derived()
   {
   	cout << "Default Constructor called for the derived class\n";
     
   }
   
   Derived(int i)
   {
   	cout << "Parameterized Constructor called for the derived class\n";
      
   }
   ~Derived(){
   	cout<<"Destructor called\n";
   }
};


int main()
{
   Base b;
   Derived d;
   Derived d1(10);
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS