Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

LiquidNRG

Function Modifiers

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

float& operator() (int i); const float& operator() (int i) const; Two functions which look very similar apart from the two const''s. Could someone give me a brief description of what they are for. I understand what const is used for in terms of variables and const arguments but not these.

Share this post


Link to post
Share on other sites
Advertisement
Well, the first version lets you change the float that is returned. For example in a vector class if i is an index into the vector then changing the returned float would change the value in the vector, so the function has a side effect (allowing the returned value to be changed) that modifies the contents of the class.

The second version says "Oi! You can''t do that!". The first const as you probably already know stops the return value from being changed, but the const on the end also tells the compiler there is no side effect of this function that changes the contents of the class it''s in.

Share this post


Link to post
Share on other sites

  

class MyClass {
public:
void foo();
};

const MyClass *myc = new MyClass;

myc->foo(); // This is not allowed, as foo() may change the

// contents of the class


////////////////////////////////////////////////////////////


class MyClass {
public:
void foo() const;
};

const MyClass *myc = new MyClass;

myc->foo(); // This time it''s OK.







// Website // Google // GameDev // NeHe // MSDN //

Share this post


Link to post
Share on other sites

  • 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!