 
 Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to initialize a const field in constructor?
Here we will see how to initialize the const type 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
Advertisements
                    