Add value to Base Class Constructor Using Member Initializer List in C++ Programming


The C++ program demonstrates the use of inheritance and constructor chaining to initialize data members of a derived class.

The program starts by including the necessary header files and defining a base class Base. The class Base has a private data member x and a constructor that takes an integer parameter a. The constructor initializes the value of x with the parameter a and also prints the value of x to the console.

A derived class Child is then defined, which publicly inherits from the base class Base. The derived class Child has a private data member y and a constructor that takes two integer parameters a and b. The constructor of the derived class Child initializes the value of y with the parameter b and also calls the constructor of the base class Base with the parameter a using the constructor chaining technique. The constructor of the derived class Child also prints the value of y to the console.

In the main() function, an object o of the derived class Child is created with two integer values of 25 and 50 passed as arguments to its constructor. The program then ends by returning 0 from the main() function, indicating that the program ran successfully.

Source Code

// Add value to Base Class Constructor
#include<iostream>
using namespace std;
class Base
{
private:
    int x;
public:
    Base(int a):x(a)
    {
        cout<<"The Value of Base X :"<<x<<endl;
    }
};
 
class Child : public Base
{
private:
    int y;
public:
    Child(int a,int b):Base(a),y(b)
    {
        cout<<"The Value of Child Y :"<<y<<endl;
    }
};
int main()
{
    Child o(25,50);
    return 0;
}
 

Output

The Value of Base X :25
The Value of Child Y :50
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples