Sign in to follow this  
chaosgame

type operator=( const type& )

Recommended Posts

I have a class sample with a method get_x() to return the value of a private pointer x. I need to access x from the function operator=() but i get an error saying that I cant access the value of x through the function because it has to be constant. should i use a cast?

Share this post


Link to post
Share on other sites
Chances are that you just need a const version of your get_x() member function.

edit: On second thought. Why can't you just access x directly? Is x a member of a base class?

Share this post


Link to post
Share on other sites
The problem is that type::get_x() is not available in const objects because of the way it is declared. In order for your function to be available to const objects, it must be declared like this:
    P const * get_x() const; 
The const says that get_x() will not modify the object. The const in "P const *" is not required, but if get_x() won't modify the object, the pointer should be restricted too. You will frequently see code like this:
    P const * get_x() const;
P * get_x();
The second function allows get_x() to return a pointer to non-const (but only for a non-const object).

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