So I've got a const pointer to a class, as follows:
const Message *msg = new Message;
The Message class has a public member function, int getSize(). But when I attempt to run int size = msg->getSize(), I get a compile-time error saying that "passing 'const Message' as `this' argument of `int Message::getSize()' discards qualifiers".
This seems pretty stupid to me - why am I not allowed to access the member functions of a const Message pointer? Is there a workaround outside of removing the const-ness?
Methods that do not modify a class should be declared as const.
1 2 3 4 5 6 7
class Foo
{
int i;
public:
void set_i( int i ) { this->i = i; } // modifies the object
int get_i() const { return i; } // does not modify the object
};
Now, if you have a const reference to a Foo, you can still get_i(), because the compiler knows that get_i() will not violate the constness of the Foo.
I think that it doesn't have to do with the constantness of the method.
He was asking about a const pointer to a class. The class by itshelf is not constant. But the pointer, that points to it, is. That means that we can change the values of the class members but we cann't change the pointer, to point to another instance of the class.
At least that is what I understand from his question.