Advanced C++: Const Member-Function

Home / Advanced C++: Const Member-Function

Advanced C++: Const Member-Function

November 24, 2015 | Article | 1 Comment

On C++, there is a way to declare a function inside a class (class’ method) as a constant function. If that is the case, the this pointer would be treated as constant pointer. Thus the function is restricted to modify any data inside its body.

To declare a function as a constant function, we must give a keyword const after the function header.

A simple code to give a hint for const member function:

#include <iostream>
using namespace std;

class Example {
int x;
public:
void setX(int value) const {
	x = value;        // wrong! Const functions are restricted
			  // to modify the data.
}
int getX() const {
	return x;        // correct!
}
};

int main() {
	Example* p;
	p = new Example;

	p->setX(3);
	cout<getX()<<endl;

	delete p;
	return 0;
}

Write and compile. Did you make it? You should get error if you write the code as is. The problem lies on function void setX(int value) const; Remember that a const function is restricted to modify the member variable, but a int getX() const; is still have read access to member variable.

Sometimes we need to change member variable by const function. To do this, member variable must be declared as mutable.

,

About Author

about author

xathrya

A man who is obsessed to low level technology.

1 Comment
  1. Advanced C++: Mutable Member - Xathrya.ID

    […] the previous article we have discussed a const member function. A const member function is a mechanism for function to […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Social media & sharing icons powered by UltimatelySocial