Reputation: 41433
I have a simple class
class Foo {
public:
float m;
Foo();
}
Foo::Foo(){
this->m = 1.0f;
}
Then I'm extending it with
class Bar: public Foo {
public:
float m;
Bar()
}
Bar::Bar(){
this->m = 10.0f;
}
I then instantiate Bar()
but Bar.m
is still 1.0f. Is there a reason for this?
Upvotes: 0
Views: 254
Reputation: 372784
In C++, you cannot override a field. Only methods can be overridden. Consequently, your declaration of the variable m
in the class Bar
is a new field that hides the base class Foo
's version of m
.
If you want to access Foo
's m
from Bar
, then you could use this syntax:
Bar::Bar(){
this->Foo::m = 10.0f;
}
Which explicitly tells the compiler to write to Foo
's version of m
. Alternatively, you can drop the this->
and just write
Bar::Bar(){
Foo::m = 10.0f;
}
Hope this helps!
Upvotes: 4