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.
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.
Following is a simple example of a const function.
When a function is declared as const, it can be called on any type of object. Non-const functions can only be called by non-const objects.
For example the following program has compiler errors.
passing 'const Test' as 'this' argument of 'int Test::getValue()' discards qualifiers
Let’s look at another example:
OUTPUT : Hello world I'm Rancho Baba Inside display() Function
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.
- Difference between const char *p, char * const p and const char * const p
- Some interesting facts about static member functions in C++
- Can we access private data members of a class without using a member or a friend function?
- Count the number of objects using Static member function
- Can C++ reference member be declared without being initialized with declaration?
- Function overloading and const keyword
- Why copy constructor argument should be const in C++?
- “static const” vs “#define” vs “enum”
- Different ways to use Const with Reference to a Pointer in C++
- Const vs Regular iterators in C++ with examples
- Can static functions be virtual in C++?
- Virtual functions in derived classes
- Functions that cannot be overloaded in C++
- Pure Functions
- Can virtual functions be inlined?
- Macros vs Functions
- fill() and fill_n() functions in C++ STL
- Return from void functions in C++
- Forward List in C++ | Set 1 (Introduction and Important Functions)
- Forward List in C++ | Set 2 (Manipulating Functions)