Single 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 a private data member x, which is initialized with the value passed as a parameter to the constructor of the class. The class Base also has a member function print(), which prints the value of x to the console.

In the main() function, an object o of class Base is created with an integer value of 25 passed as an argument to its constructor. The print() function of the object o is then called to display the value of x.

The use of a constructor in this program ensures that the private data member x of the class Base is always initialized with a value, which can be useful in preventing uninitialized variables. The program ends by returning 0 from the main() function, indicating that the program ran successfully.

Source Code

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

Output

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