Link to home
Start Free TrialLog in
Avatar of Fallen_Knight
Fallen_Knight

asked on

Readonly Class Instance Attributes, How?

Is it possible to have a attribute of a class readonly to the outside world, but to the class itself, writeable.

I'd like to not have to implement a accssor function, but i'd also do not want to have to worry about code outside the class changeing the value of these pointers.

Is this possible??

Thanks for the help.
Fallen
Avatar of Managu
Managu

This is not possible in C++; as you suggest, the standard method to deal with this is accessor methods.
accessor methods is the way to go to solve that problem.

However, if you write the accesor method inline the compiler will often optimize it away:

class X {
private:
   int dont_touch_this;

public:
   int read_only() const { return dont_touch_this; }
};


If you then write something like:

int x = Xobj.read_only();

The compiler will treat this as if you had written:

int x = Xobj.dont_touch_this;

No function call anywhere...

Making the function inline  - as I did above - and telling the compiler to generate inline functions inline (this is normally the default for non-debug builds) does that kind of magic. One clue here is to make the accessor functions small, they should be accessor functions and not much else. The reason is that big functions tend to become regular functions even if they are defined inline.

Taking the address of a function and call it through pointer or call it through virtual mechanism also makes the function not inline for that call. However, other direct calls to the function may still be done inline without any actual funciton call taking place.

Alf
ASKER CERTIFIED SOLUTION
Avatar of burcarpat
burcarpat

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Fallen_Knight

ASKER

Thats what i was looking for, but i was hopeing for an easier solution:)

And compile time-checking not run-tim. I would have though there was an easier way to do this. a semi private class varible or something.

But ah well, thanks for the answer!