×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object 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

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.