Archived

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

Enselic

error in a simple "get-method"

Recommended Posts

This doesn''t make any sense to me. I have this:

class core_c
{
public:
    renderer_c*     rendererPointer() const;
    
private:
    renderer_c      _Renderer;
};

renderer_c* core_c :: rendererPointer() const
{
    return &_Renderer;
}
   
This is spitten out when I try to compile it with VC++.NET:

error C2440: ''return'' : cannot convert from ''const renderer_c *'' to ''renderer_c *'' Conversion loses qualifiers
   
Why is this? Taking away the const keyword is not only bad design, but it means that I have to convert more const-methods to non-consts one.

Share this post


Link to post
Share on other sites
OK, I have to admit that I''m not fully up on how const works is situations like this, but my understanding of it is this:

1. Saying that the member function is const means you''re promising not to change any member variables.
2. Returning a pointer to a member variables means that the variable can be changed.
3. 1 & 2 conflict

To solve this you should either:

1. make the member function return type const
2. make the member function non-const

If this is wrong in anyway then please correct me,

Enigma

Share this post


Link to post
Share on other sites
Oh well, I guess I'll have to make them non-constant since the point is really just to encapsulate the core classes I have, in ONE core-class. I wonder why I didn't just make the members private in the first place since the point is that the core classes should be editable.

[edited by - Enselic on November 16, 2003 10:52:06 AM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Be warned, you cant use non const member functions on const objects, you might be better off creating two of the same function, one for const, one for none const.

Share this post


Link to post
Share on other sites