Multiple Value Member Initializer List in C++ Programming


Member initializer list is the place where non-default initialization of these objects can be specified. Initializer list is used to initialize data members. The syntax begins with a colon(:) and then each variable along with its value separated by a comma.

  • The program starts by including the necessary header files and defining a class Base. The class Base has two private data members x and y, which are initialized with the values passed as parameters to the constructor of the class. The class Base also has a member function print(), which prints the values of x and y to the console.
  • In the main() function, an object o of class Base is created with two integer values of 25 and 35 passed as arguments to its constructor. The print() function of the object o is then called to display the values of x and y.
  • The use of a constructor with multiple parameters in this program ensures that the private data members x and y of the class Base are always initialized with the specified values, which can be useful in preventing uninitialized variables and maintaining encapsulation.
  • The program ends by returning 0 from the main() function, indicating that the program ran successfully.

Source Code

//Member Initializer List
//
#include<iostream>
using namespace std;
class Base
{
private:
    int x,y;
public:
    Base(int a,int b):x(a),y(b){}
    void print(){
    cout<<"X : "<<x<<endl;
    cout<<"Y : "<<y<<endl;
    }
};
 
int main()
{
    Base o(25,35);
    o.print();
    return 0;
}
 

Output

X : 25
Y : 35
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