
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
How to initialize const member variable in a C++ class?
Here we will see how to initialize the const type member variable using constructor?
To initialize the const value using constructor, we have to use the initialize list. This initializer 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.
Example
#include <iostream> using namespace std; class MyClass{ private: const int x; public: MyClass(int a) : x(a){ //constructor } void show_x(){ cout << "Value of constant x: " << x ; } }; int main() { MyClass ob1(40); ob1.show_x(); }
Output
Value of constant x: 40
- Related Articles
- How to initialize a const field in constructor?
- Const member functions in C++
- How to modify a const variable in C?
- How to access a derived class member variable by an interface object in Java?
- How do we initialize a variable in C++?
- What is the scope of a public member variable of a class in C#?
- What is the scope of a private member variable of a class in C#?
- What is the scope of a protected member variable of a class in C#?
- What is the scope of a protected internal member variable of a class in C#?
- How to initialize a data frame with variable names in R?
- How many ways are there to initialize a final variable in java?
- How to instantiate member inner class in Java?\n
- Can a C++ variable be both const and volatile?
- Class with a constructor to initialize instance variables in Java
- How to convert a sub class variable into a super class type in Java?

Advertisements