Jump to content
  • Advertisement
Sign in to follow this  
lane_mcnair

weird compiler error

This topic is 3572 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

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!