Wednesday, August 10, 2011

Calling Const Functions

I learned today that if you have a const object then the compiler will only allow you to call const methods on that object (i.e. methods which are guaranteed not to changed the state of that object). So how do you tell the compiler that a method won't change the object? Put const at the end of the method declaration:
void MyClass::myConstFunction() const
{
   ....
}

I hit this issue when I was writing a copy constructor with the following signature:
man(const man& m)

I tried calling m.getName() to retrieve the man's name but because I didn't declare getName() as a const method I got the following error (I was using Visual Studio 2008):

error C2662: 'man::getName' : cannot convert 'this' pointer from 'const man' to 'man &'

I realised during my debugging that I didn't need to call a getter because the copy constructor could access the private members of the other man object. Here's the great article that helped me.