Program Demonstrates Parameterized Constructor In Multilevel Inheritance In C++

LEVEL: Beginner

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code

Code


To copy code: Click View Source “View Source” on the right of this code snippet.


Background and Explanation of the code


In the above program the class derv2 is derived publicly from derv1 class which in turn is derived from base class publicly.Each class must pass all arguments required by each preceding base class using their constructor.The statement

derv2 d (10, 20, 30);

in main ( ) creates an object d of derv2 class that invokes constructor with three parameters which further calls the derv1’s constructor with two parameters which in turn calls the base’s single parameter constructor.The base’s class constructor initializes its data member x and then the control is transferred to derv1’s class constructor which initializes its data member y and after completing its execution the control finally returns to the derv2’s class constructor which initialize its data member z.

OUTPUT

Base’s single parameter constructor executed

Derv1’s constructor with two parameters executed

Derv2’s constructor with three parameters executed