Home »
C+ programs »
C++ constructor, destructor programs
C++ program to demonstrate example of member initializer list
Learn about the member initializer list in C++, how to implement member initializer list in C++ program?
[Last updated : March 02, 2023]
In this program we will learn to create member initializer list program in c++ programming language.
Member Initializer List Program in C++
// C++ program to demonstrate example of
// member initializer list
#include <iostream>
using namespace std;
//Class declaration.
class Demo {
//Private block to declare data member( X,Y )
//of integer type.
private:
const int X;
const int Y;
//Public block of member function to
//access data members.
public:
//Const member can only be initialized with
//member initializer list.
//Declaration of defalut constructor.
Demo()
: X(10)
, Y(20){};
//Declaration of parameterized constructor to
//initialize data members by member intializer list.
Demo(int a, int b)
: X(a)
, Y(b){};
//To display output onn screen.
void Display();
}; //End of class
//Definition of Display() member function.
void Demo::Display()
{
cout << endl
<< "X: " << X;
cout << endl
<< "Y: " << Y << endl;
}
int main()
{
//Ctor automatically call when object is created.
Demo d1; //Default constructor
Demo d2(30, 40); //Parameterized constructor.
//Display value of data member.
cout << "Value of d1: ";
d1.Display();
cout << "Value of d2: ";
d2.Display();
return 0;
}
Output
Value of d1:
X: 10
Y: 20
Value of d2:
X: 30
Y: 40