Duplicate variable names

Started by
6 comments, last by DrEvil 18 years, 9 months ago
What does the standard say about duplicate variable names in an inheritance hierarchy? For example: class parent { public: float mass; } class child : public parent { public: float mass; } Now if you try to access mass from an instance of the child class, does the standard define that it should use the childs version? This is assuming there aren't other hints to the compiler, like the parent::mass being private, or the programmer explicitly scoping the use of the variable to one or the other. I thought I had read before this could be compiler dependant and therefor should not be used, but I just wanted to verify one way or the other. So other than the general messyness and ambiguity of doing this from a readability standpoint, does the standard define an 'order' of resolution for variable names? Thanks
Advertisement
The child's identifier will hide the parent's identifier. It's standardized behavior. And privacy does not affect which one is chosen; name resolution is independent of access specifiers.
Generally code in the child class will use child::mass, and code in the parent class will use parent::mass.

The standard does define the order in which the compiler searches for the name, and the first scope it looks in after function scope and class scope is the scope of base classes.

But, if you then create a new class that inherits from both classes, then you'd have ambiguity, and you'd have to explicitly resove the name.
MrEvil, may I introduce DrEvil?
DrEvil, MrEvil.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
hehe, where are the Miss Evils?
Quote:Original post by DrEvil
hehe, where are the Miss Evils?


Probably somewhere in the vicinity of the singletons.
SlimDX | Ventspace Blog | Twitter | Diverse teams make better games. I am currently hiring capable C++ engine developers in Baltimore, MD.
For the record, your compiler may have an option that will warn you if name hiding like this occurs, as it can lead to some tricky bugs that aren't immediately obvious unless you're familiar with all the semantics of name hiding. I know at least GCC3.x have this option and I believe I've seen it in VC7 as well.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

Thanks for the info everyone.

This topic is closed to new replies.

Advertisement