
- 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
Const member functions in C++
The const member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided.
A const member function can be called by any type of object. Non-const functions can be called by non-const objects only.
Here is the syntax of const member function in C++ language,
datatype function_name const();
Here is an example of const member function in C++,
Example
#include<iostream> using namespace std; class Demo { int val; public: Demo(int x = 0) { val = x; } int getValue() const { return val; } }; int main() { const Demo d(28); Demo d1(8); cout << "The value using object d : " << d.getValue(); cout << "\nThe value using object d1 : " << d1.getValue(); return 0; }
Output
The value using object d : 28 The value using object d1 : 8
- Related Articles
- How to initialize const member variable in a C++ class?
- What are static member functions in C#?
- How static variables in member functions work in C++?
- What are member functions of a class in C#?
- Difference between const int*, const int * const, and int const * in C/C++?
- Difference between const int*, const int * const, and int const * in C
- Difference between const char* p, char * const p, and const char * const p in C
- Const Qualifier in C
- Const cast in C++
- Declare a const array in C#
- enum vs. const vs. #define in C/C++
- What is the difference between const int*, const int * const, and int const *?
- What is the const Keyword in C++?
- Const vs Static vs Readonly in C#
- Difference between #define and const in C

Advertisements