views:

49

answers:

3
class Base
{
public:
 type1 m_Pants;
};

class Derived : Base
{
public:
 type2 m_Pants
};

This essentially didn't get flagged as an error, but was creating all kinds of clobbering and issues throughout a project.

Does anyone know of a technicality that wouldn't flag this?

+1  A: 

It does exactly what it's supposed to do. The derived shadows the base.

Matthew Flaschen
Care to explain the downvote?
Matthew Flaschen
Functions can be overloaded and overridden. Members cannot. `Derived::m_pants` and `Base::m_pants` are two different variables completely. If you use `std::cout << sizeof (Base) << ' ' << sizeof (Derived) << std::endl;` in a small test program, you would see that `Derived` is larger in size than `Base`. You could even make the variables use the same name and type, but they're still different variables because they belong to different classes.
Dustin
Ah, you changed the term you used from "overrides" to "shadows", thus invalidating my comment. Thanks for fixing it. :)
Dustin
@Dustin, thank you for improving my terminology.
Matthew Flaschen
+4  A: 

It isn't getting flagged as an error because it's not an error. There's nothing that says you can't have members in a derived class that are named the same as members in a base class.

If you have an object obj of type Derived, then obj.m_Pants refers to the m_Pants in Derived. If you want to refer to the base member, you can do so using obj.Base::m_Pants.

If you are in a member function of Base or have a Base* that points to an object of type Derived, then m_Pants always refers to the member of Base, because in those contexts there is no knowledge of the class Derived and its members.

Well, it's not a code error; it's almost certainly a design error.

James McNellis
I've tried `int val = obj.Base::m_Pants` in C++Builder6 and got compilation error: **E2247 'Base::m_Pants' is not accessible** (m_Pants is public)
Alexander Malakhov
It compiles only with get/set funcs `public: int getBase(){ return Base::m_Pants}`
Alexander Malakhov
@Alexander: Well, in the example code, `Derived` inherits privately from `Base`, so, you're right that that wouldn't work. You'd need to change it to inherit publicly.
James McNellis
Although it wasn't exactly 'm_Pants', the name used was extremely general and apparently very popular.
John Smith
+1  A: 

One variable is shadowing the other. It's just like if you declared a member variable name x and then had a member function which declared its own x, except that here, one of the variables is in the base class and one is in a derived class.

int func(int x)
{
    return x;
}

would return the value of x you passed in, not that of the member variable x. One variable "shadows" the other. It's why it's a good idea to name your variables so that they don't ever have names which could clash.

Jonathan M Davis