can't access member functions of const *class

Aug 4, 2008 at 3:06am
Hey all,

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?
Aug 4, 2008 at 3:46am
You want a constant pointer and not a pointer to a constant object. So you should use
Message *const msg = new Message;


const Message *msg = new Message; is a pointer to an object named Message.

Message *const msg = new Message; is a constant pointer to an object named Message.


It helps if you read it with reverse order:

const Message *msg
'msg' is a pointer to an object named "Message" which is a constant

Message *const msg
'msg' is a constant pointer to an object named "Message".

Hope this helps
Last edited on Aug 4, 2008 at 3:49am
Aug 4, 2008 at 3:52am
Because the method is not const correct. (Hmm, I'm sure that I just recently responded to this very issue... but I can't find it.)

Take a look through the C++FAQ-Lite
http://www.parashift.com/c++-faq-lite/const-correctness.html

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.

Hope this helps.
Aug 4, 2008 at 4:05am
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.
Last edited on Aug 4, 2008 at 4:06am
Aug 4, 2008 at 4:10am
Actually, Duoas answered the question. Everything's peachy now. Thank you all very much for your quick responses!
Aug 4, 2008 at 4:13am
Oh, ok. I just though you wanted a constant pointer instead of a pointer to a constant object.
Sorry about that.
Topic archived. No new replies allowed.