Const member functions in C++
Last Updated :
11 Jan, 2025
Constant member functions are those functions that are denied permission to change the values of the data members of their class. To make a member function constant, the keyword const is appended to the function prototype and also to the function definition header.
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
The const member function can be defined in three ways:
1. For function declaration within a class.
return_type function_name() const;
Example:
int get_data() const;
2. For function definition within the class declaration.
return_type function_name () const
{
//function body
}
Example:
int get_data() const
{
//function body
}
3. For function definition outside the class.
return_type class_name::function_name() const
{
//function body
}
Example:
int Demo :: get_data() const
{
}
Important Points
- 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 practice to make as many functions const as possible so that accidental changes to objects are avoided.
Examples of Const Member Functions
Example 1
The below C++ program demonstrates that data members can be updated in a member function that is not constant.
C++
// C++ program to demonstrate that data members can be
// updated in a member function that is not constant.
#include <iostream>
using namespace std;
class Demo {
int x;
public:
void set_data(int a) { x = a; }
// non const member function
// data can be updated
int get_data()
{
++x;
return x;
}
};
main()
{
Demo d;
d.set_data(10);
cout << d.get_data();
return 0;
}
Example 2
The below C++ program demonstrates that data cannot be updated in a Constant member function.
C++
// C++ program to demonstrate that data cannot be updated
// in a Constant member function
#include <iostream>
using namespace std;
class Demo {
int x;
public:
void set_data(int a) { x = a; }
// constant member function
int get_data() const
{
// Error while attempting to modify the data
// member
++x;
return x;
}
};
main()
{
Demo d;
d.set_data(10);
cout << endl << d.get_data();
return 0;
}
Output
./Solution.cpp: In member function 'int Demo::get_data() const':
./Solution.cpp:17:11: error: increment of member 'Demo::x' in read-only object
++x;
^
Example 3
The below C++ code demonstrates how to define constant member functions outside the class definition and showcases the usage of a constant member function to set and retrieve the value of a private member variable.
C++
// Constant member function defined outside the class
#include <iostream>
using namespace std;
class Demo {
int x;
public:
void set_data(int);
// const member function
int get_data() const;
};
// Function definition for setting the value of x.
void Demo::set_data(int a) { x = a; }
// Function definition for retrieving the value of x (const
// member function).
int Demo::get_data() const { return x; }
main()
{
Demo d;
// Set the value of x to 10 using the non-const member
// function.
d.set_data(10);
// Print the value of x using the const member function.
cout << d.get_data();
return 0;
}
Example 4
The below C++ program demonstrates that const functions can be called by non-const objects.
C++
// C++ program to demonstrate that const functions can be
// called by non const objects
#include <iostream>
using namespace std;
class Test {
int value;
public:
Test(int v = 0) { value = v; }
// const member function
int getValue() const { return value; }
};
int main()
{
// non const object
Test t(20);
cout << t.getValue();
return 0;
}
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.
C++
// C++ program that demonstrate that non-const functions can
// not be called by const objects
#include <iostream>
using namespace std;
class Test {
int value;
public:
Test(int v = 0) { value = v; }
// non const member function
int getValue() { return value; }
};
int main()
{
// const object
const Test t;
cout << t.getValue();
return 0;
}
Output
./d869c7ba-f199-4a67-9449-3936b5db4c5b.cpp: In function 'int main()':
./d869c7ba-f199-4a67-9449-3936b5db4c5b.cpp:14:24: error: passing 'const Test' as 'this' argument of 'int Test::getValue()' discards qualifiers [-fpermissive]
cout << t.getValue();
Let’s look at another example:
C++
// Demonstration of constant object,
// show that constant object can only
// call const member function
#include <iostream>
using namespace std;
class Demo {
int value;
public:
Demo(int v = 0) { value = v; }
void showMessage()
{
cout << "Hello World We are Tushar, "
"Ramswarup, Nilesh and Subhash Inside"
" showMessage() Function"
<< endl;
}
// const member function
void display() const
{
cout << "Hello world I'm Rancho "
"Baba Inside display() Function"
<< endl;
}
};
int main()
{
// Constant object are initialised at the time of
// declaration using constructor
const Demo d1;
// d1.showMessage();Error occurred if uncomment.
d1.display();
return (0);
}
OutputHello world I'm Rancho Baba Inside display() Function
Similar Reads
Static Member Function in C++
The static keyword is used with a variable to make the memory of the variable static once a static variable is declared its memory can't be changed. To know more about static keywords refer to the article static Keyword in C++. Static Member in C++ Static members of a class are not associated with t
4 min read
Constructors in C++
In C++, constructor is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects. The constructor in C++ has the same name as the class or structure. Example: [GFGTABS] C++ #include <iostream> using name
6 min read
Functions in C++
A function is a building block of C++ programs that contains a set of statements which are executed when the functions is called. It can take some input data, performs the given task, and return some result. A function can be called from anywhere in the program and any number of times increasing the
9 min read
Function Pointer in C
In C, a function pointer is a type of pointer that stores the address of a function, allowing functions to be passed as arguments and invoked dynamically. It is useful in techniques such as callback functions, event-driven programs, and polymorphism (a concept where a function or operator behaves di
6 min read
Function Pointer in C++
Prerequisites: Pointers in C++Function in C++ Pointers are symbolic representations of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Iterating over elements in arrays or other data structures is one of the main use of point
4 min read
Inline Functions in C++
In C++, inline functions provide a way to optimize the performance of the program by reducing the overhead related to a function call. When a function is specified as inline the whole code of the inline function is inserted or substituted at the point of its call during the compilation instead of us
6 min read
Return From Void Functions in C++
Void functions are known as Non-Value Returning functions. They are "void" due to the fact that they are not supposed to return values. True, but not completely. We cannot return values but there is something we can surely return from void functions. Void functions do not have a return type, but the
2 min read
std::function in C++
The std::function() in C++ is a function wrapper class which can store and call any function or a callable object. In this article, we will learn about std::function in C++ and how to use it in different cases. Table of Content What is std::function in C++?Example of std::functionMember Functions of
6 min read
vector data() function in C++ STL
In C++, the vector data() is a built-in function used to access the internal array used by the vector to store its elements. In this article, we will learn about vector data() in C++. Letâs take a look at an example that illustrates the vector data() method: [GFGTABS] C++ #include <bits/stdc++.h
2 min read
C++ Function Call By Pointer
Several ways exist in which data (or variables) could be sent as an argument to a function. Two of the common ones are Passing by Value and Passing by Reference. Example: C/C++ Code // C++ Program to demonstrate // Pass by value and // Pass by reference #include <iostream> using namespace std;
3 min read