Sign in to follow this  
lane_mcnair

weird compiler error

Recommended Posts

I've been programming in c++ for a few years, and I've never come across this strange compiler error. I'm using MinGW as my compiler. I've created an example that demonstrates the error when compiled.

#include <windows.h>

class test0
{
     public:
          void SaySomething()
          {
               MessageBox(NULL, "Something.", "!", MB_OK);
          }
};
class test1
{
     public:
          const test0* GetObject()
          {
               return &object;
          }
     private:
          test0 object;
};
class test2
{
     public:
          test2(test1* t): owner(t)
          {
               
          }
          void SaySomething()
          {
               owner->GetObject()->SaySomething();
          }
     private:
          test1* owner;
};

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
     test1 t1;
     test2 t2(&t1);
     t2.SaySomething();
     return 0;
}

In this case, the error would read:
Quote:
error: passing `const test0' as `this' argument of `void test0::SaySomething()' discards qualifiers
I really have no idea why this is happening. All I know is that if I change the line "owner->GetObject()->SaySomething();" to "const_cast<test0*>(owner->GetObject())->SaySomething();" it fixes the problem. Why does the constness of my object pointer matter? Could someone please explain this to me? I really don't like using const_cast, and I'm hoping that by learning why the error happens, I can fix my code so that I don't have to. Thank you.

Share this post


Link to post
Share on other sites
You should read up on Const-correctness. Basically though, a const object cannot be modified, so any functions you call on a const object must be const functions - i.e. they must not modify the object in any way. In your case, SaySomething() doesn't modify the object, but it hasn't been declared const either - add the keyword 'const' after the parameter list.
class test0
{
public:
void SaySomething() const // note the const keyword
{
MessageBox(NULL, "Something.", "!", MB_OK);
}
};

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this