Jump to content
  • Advertisement
Sign in to follow this  
DrEvil

Duplicate variable names

This topic is 4755 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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

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
Quote:
Original post by DrEvil
hehe, where are the Miss Evils?


Probably somewhere in the vicinity of the singletons.

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!