×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

Initialization of class's const data member in C++

A const data member cannot be initialized at the time of declaration or within the member function definition.

To initialize a const data member of a class, follow given syntax:

Declaration

const data_type constant_member_name;

Initialization

class_name(): constant_member_name(value)
{
}

Example of initialization of class's const data member in C++

Let's consider the following example/program

#include <iostream>
using namespace std;

class Number {
 private:
  const int x;

 public:
  // const initialization
  Number() : x(36) {}
  // print function
  void display() { cout << "x=" << x << endl; }
};

int main() {
  Number NUM;
  NUM.display();

  return 0;
}

Output

x=36

Explanation

In this program, Number is a class and x is a constant integer data member, we are initializing it with 36.

Here,

Declaration of const data member is:

const int x;

Initialization of const data member is:

Number():x(36){}

Related Tutorials

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.