Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

constant function
c++

What are const functions in C++?

Rabia Zareen

The const function

A function declared with the const keyword is a constant function. Constant functions are popular due to their ability to prevent accidental changes to the object’s value.

Syntax

Syntax

The syntax of the const function is as follows:

int getValue() const 

Code

Following is the sample code for the const function. In the code below, getValue() is the constant function, s is a const object, and s1 is a non- const object:

#include<iostream>
using namespace std;
class sample {
   int val;
   public:
   sample(int x = 0) {
      val = x;
   }
   int getValue() const {
      return val;
   }
};
int main() {
   const sample s(20);
   sample s1(2);
   cout << "The value using object d : " << s.getValue();
   cout << "\nThe value using object d1 : " << s1.getValue();
   return 0;
}
Constant member function

const function use cases

const member functions have the following use cases:

  • A const function can be called by either a const or non-const object.
  • Only a non-const object can call a non-const function; a const object cannot call it.
#include<iostream>
using namespace std;
class sample {
   int val;
   
   public:
   sample(int x = 0) {
      val = x;
   }
   int getValue() const {
      return val;
   }
   int getValue1() {
      return val;
   }
};

int main() {
   const sample s(20);
   sample s1(2);
   
   cout << "The const function called by const object s : " << s.getValue();
   cout << "\nThe const function called by non-const object s1 : " << s1.getValue();
   cout << "\nThe non-const function called by non-const object s1 : " << s1.getValue1();
   //cout << "\nThe non-const function called by const object s : " << s.getValue1(); //Gives compiler error because
   return 0;
}
const function use cases

Explanation

In the code above, the function getvalue() is a const member function, whereas getvalue1() is a non-const member function. Moreover, s is a const, whereas s1 is a non-const object.

  • There is no error when s calls getValue(), but when s calls getValue1(), the compiler gives an error, as shown below.
  • There is no error when s1 calls either getValue()or getValue1().

Note: We can uncomment the code in line 25 in the main function to check the following compiler error due to the constant object calling a non-constant member function.

Compiler error

RELATED TAGS

constant function
c++

CONTRIBUTOR

Rabia Zareen
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring