Sign in to follow this  
DrEvil

Duplicate variable names

Recommended Posts

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

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