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?
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
ASKER
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 ==.
if ( x == 0 ) {...} // not allowed
if ( 0 == x ) {...} // allowed
to prevent accidental use of = instead of ==.
ASKER
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.