Link to home
Start Free TrialLog in
Avatar of phoffric
phoffric

asked on

C++ Accidental Access to Private Object Variable

Given a class with a private variable and a public getter method, if a programmer were to return a reference to the private variable, then users of that method could have direct modifiable access to that private variable (i.e., modify the variable value without using an object method).

I don't like this. (Tough luck on me, I guess. But why would the C++ standard allow this?)

Is there a way to keep private variables truly private so that the above cannot happen?
ASKER CERTIFIED SOLUTION
Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

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 phoffric
phoffric

ASKER

Darn, I am being considered for a lead position at a new company, so I started think about how someone can mess things up and thought about these kinds of problems. I knew about your suggestions, but I guess it will be the code reviews that will have to save us from this type of coding from getting into production. Without the code reviews to catch this, no doubt initial systems testing will pass fine. But someday, someone would start modifying these private object variables using their own "local" variables.

I heard that C can shoot you in the foot; and that C++ tries to improve on that; but when the coding goes too far awry, C++ can blow off your face.
C++, like C, is a very low-level programming language. It gives you the tools but doesn't really stop you abusing them. Just like a hammer, when used incorrectly, can cause havoc so can C/C++. If you are the team lead you should ensure you have a coding standard document and ensure all your team adhere to it.  If you don't have one then this is a good place to start.
Thanks! I have worked with government coding standards; yet I have not seen the protection required to avoid the above potential maintance issue. There were some useful things like:
 if ( x == 0 ) {...} // not allowed
 if ( 0 == x ) {...} // allowed
to prevent accidental use of = instead of ==.