- Home
- Course Category
- Course Result
- Course Detail
Hot Line: 0124-2383121
Course Introduction
Const member functions in C++
Like member functions and member function arguments, the objects of a class can also be declared as const. an object declared as const cannot be modified and hence, can invoke only const member functions as these functions ensure not to modify the object.
A const object can be created by prefixing the const keyword to the object declaration. Any attempt to change the data member of const objects results in a compile-time error.
Syntax:
const Class_Name Object_name;
When a function is declared as const, it can be called on any type of object, const object as well as non-const objects.
Whenever an object is declared as const, it needs to be initialized at the time of declaration. however, the object initialization while declaring is possible only with the help of constructors.
A function becomes const when the const keyword is used in the function’s declaration. The idea of const functions is not to allow them to modify the object on which they are called.
It is recommended the practice to make as many functions const as possible so that accidental changes to objects are avoided.
Source Code:Const Keyword
/* C++ Program - to illustrate class objects as static */ #includeusing namespace std; class Test { int value; public: Test(int v = 0) {value = v;} // We get compiler error if we add a line like "value = 100;" // in this function. int getValue() const {return value;} }; int main() { Test t(20); cout< When the above code is compiled and executed, it produces the following result −
20// Demonstration of constant object, // show that constant object can only // call const member function #includeusing namespace std; class Demo { public: void showMessage() { cout<<"Hello World You are Inside" " showMessage() Function"< When the above code is compiled and executed, it produces the following result −
Hello world You are inside display() FunctionOther Object Oriented Programming concepts