...

/

Sequence for Calling Constructors

Sequence for Calling Constructors

Learn about the sequence for calling constructors during inheritance.

We'll cover the following...

Problem

Write a program that displays the sequence for calling constructors during inheritance.

Coding solution

Here is a solution to the problem above.

Press + to interact
// Constructor inheritance
#include <iostream>
class Sample
{
protected :
int count ;
public :
Sample( )
{
count = 0 ;
std :: cout << "Reached 0-arg Ctor of Sample" << std :: endl ;
}
Sample ( int k )
{
count = k ;
std :: cout << "Reached 1-arg Ctor of Sample" << std :: endl ;
}
} ;
class NewSample : public Sample
{
private :
int newcount ;
public :
NewSample( )
{
newcount = count * 20 ;
std :: cout << "Reached 0-arg Ctor of NewSample" << std :: endl ;
}
NewSample ( int k ) : Sample ( k )
{
newcount = count * 20 ;
std :: cout << "Reached 1-arg Ctor of NewSample" << std :: endl ;
}
} ;
int main( )
{
std :: cout << "Ctor calling order for i :" << std :: endl ;
Sample i ;
std :: cout << "Ctor calling order for j :" << std :: endl ;
NewSample j ;
std :: cout << "Ctor calling order for k :" << std :: endl ;
NewSample k ( 30 ) ;
}
...