Reputation: 1017
I am learning about OOP with c++ and have run into a situation I don't quite understand.
{Understanding the poor practice of public data members and assuming pointers are not NULL}:
...
class Foo {
public: int a = 0;
}
class Bar: public Foo {
public: int a = 1;
}
void display (Foo * in) {
if(in->a)
cout << "I'M A BAR" << endl;
else
cout << "I'M A FOO" << endl;
}
int main() {
Foo * BAR = new Bar;
display(BAR); //Displays "I'M A FOO"
return 0;
}
And after a little more tinkering I found that if I instead use constructors to set non const int a values to 0 and 1 respectively AND also output the value form the constructor I see that the value is in fact being set to 1 in BAR, but being evaluated as 0 inside the display function.
I am sorry if this does not make sense, I doubt I really understand well enough to ask the right question, but I am wondering why BAR is not treated like a Bar inside display and how to get it to do so (if possible while still using the base class pointer as an argument).
Upvotes: 0
Views: 45
Reputation: 477512
Your code makes sense, but it is probably not what you think.
Your class Bar
has two members called a
, one is Bar::a
, and one is Bar::Foo::a
, the member of the Foo
base class.
When you access either a Foo
or a Bar
object through a pointer, like p->a
, then you always get the a
member of the Foo
base subobject.
In other words, you cannot "override" data members.
The other code you allude to only has one data member, and it would look like this:
struct Foo
{
int a;
Foo() : a(0) { }
protected:
explicit Foo(int n) : a(n) { }
};
struct Bar : Foo
{
Bar() : Foo(1) { }
};
Note how both Foo
and Bar
only have one single data member a
in this setup.
Upvotes: 4