Sign in to follow this  

c++: const after a function declaration

This topic is 3478 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

It "promises" that the function will not modify the state of the class. This signifies that it's ok to call this function from a const instance. This is a common modifier for functions that don't do any real work, such as simple variable getters.

Share this post


Link to post
Share on other sites
It means the function can't modify any members of the class.


class stuff
{
public:
int RowCount() const
{
//can't modify x here
}

private:
int x;

};





An example for using it for functions is to display data from that class, rather than modify it.

Share this post


Link to post
Share on other sites

class MyClass
{
public:
void MyFunc() { var = 3; }

void MyConstFunc() const
{
// can't modify var in here, because this function
// promises that it is const
var = 3; // compiler error
}

private:
int var;
}

MyClass c;

c.MyFunc(); // ok
c.MyConstFunc(); // ok

const MyClass m;
m.MyConstFunc(); // ok
m.MyFunc(); // not ok, it's not const

Share this post


Link to post
Share on other sites
To be more precise: It forbids the member function to alter any non-mutable members.
So this would still work:

class MyClass
{
public:
void MyFunc() { var = 3; }

void MyConstFunc() const
{
// can modify var because it is mutable
var = 3;
}

private:
mutable int var;
};

Share this post


Link to post
Share on other sites
It's funny that you should be asking about this, as I am literally currently reading this information in the book right now haha. I'm brushing up on my C++ as I haven't done it in a while, before I program some stuff :)


Also when you're writing methods and have const parameters/arguments, you have to use constant methods when working with that object.


//header file

class Rectangle
{

public:
double getArea() const;
int compareRect(const Rectangle& otherRect) const;

private:
double length;
double width;


};


//source file

double Rectangle::getArea() const
{
return length * width;
}

int Rectangle::compareRect(const Rectangle& otherRect) const
{
if ( this->getArea() > otherRect.getArea() )
return 1; //return 1 if this one is larger
else if ( this->getArea() < otherRect.getArea() )
return -1; //return -1 if this one is smaller
else
return 0; //if the same, return 0
}








While that's not perfect, kinda something like that if you get that.

Edit: Fixed a missing '&' in my code :)

Edit2: Book makes a note that the const keyword effectively turns the this pointer into a const type as well. Also makes note that one should always declare member fucntions that do not change the object for which they are called as const.

Share this post


Link to post
Share on other sites
Sign in to follow this