Initialized Const variable using Member Initializer List in C++ Programming


A constant is a variable whose value cannot change once it has been assigned. To declare any variable as constant, we use static and final modifiers. It is also known as non-access modifiers. To initialize the const value using constructor, we have to use the initialize list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma .

The program demonstrates the use of a constant data member in a C++ class.

  • The class Base has a private constant integer data member x, which is initialized using a constructor with a parameter a. The const keyword is used to make sure that the value of x cannot be modified once it is initialized.
  • The constructor of the Base class takes an integer value a, which is used to initialize the constant data member x. The cout statement in the constructor prints the value of x.
  • In the main function, an object o of the Base class is created by passing the value 50 as an argument to the constructor. The return 0; statement at the end of the main function indicates the successful termination of the program.

Source Code

//Initialized Const variable using Member Initializer List
#include<iostream>
using namespace std;
class Base
{
private:
    const int x;
public:
    Base(int a):x(a)
    {
        cout<<"The Value of X :"<<x;
    }
};
int main()
{
    Base o(50);
    return 0;
}
 

Output

The Value of X :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