Whats in this post?
- Background and Explanation of the code
To copy code: Click “View Source” on the right of this code snippet.
Background and Explanation of the code
In this program, first we define classes base1 and base2 containing a constructor with single parameter for initializing their data member x and y respectively.Then we derive a class derv publicly from both base1 and base2.Then derived class declaration is shown as
class derv : public base1, public base2
It specifies that the class derv is derived from the base classes base1 and base2 in order.A constructor with two parameters
derv (int xx, int yy) : base2 (yy), base1 (xx)
is defined in the derived class derv for passing xx and yy arguments by explicitly invoking the constructors of base1 and base2 classes respectively.However the constructors are executed in order base1 ( ), base2 ( ) as specified in the derivation list that appears in the derived class declaration.
The statement derv d (10, 20); on execution creates an object d of the derived class that initialize 10 to data member x of base1 class and 20 to data member y of base2 class.The output shows that the execution of base class constructor depends only upon the derivation list specified in the declaration of derived class and not the order in which base class constructor are explicitly invoked in the derived class.
Base1’s single parameter constructor executed x = 10
Base2’s single parameter constructor executed y = 20
Derv’s constructor with two parameters executed