Open In App
Related Articles

Const member functions in C++

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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;
}

                    

Output
11

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;
}

                    

Output
10

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;
}

                    

Output
20

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);
}

                    

Output
Hello world I'm Rancho Baba Inside display() Function

FAQs on Const Member Functions

Q1. Can const objects of a class call non-const member functions?

Answer:

No,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.

Q2. Can non-const objects of a class call const member function?

Answer:

When a function is declared as const, it can be called on any type of object.



Last Updated : 28 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads