I may be understanding inheritance wrong but say if:
I have base class called Base and a derived class of Base called Derived,
In a function of the Derived class, can I access the Base object of the Derived class? I guess a bit like *this but of object type Base ?
EDIT: I am overriding a function Base::foo() in the Derived class, but in this overridden function Derived::foo() i want to call the original function with the Base object.
Derived::foo() const {
double Derived::foo() const {
// s is a variable only associated with Derived
double x;
x = s + Base.foo(); // this is the line i dont know what im doing?!
return x;
}
A Derived*
is implicitly convertible to Base*
, so you can just do:
const Base *base = this;
Although you don't usually need this because any member of Base
is inherited by Derived
.
But if foo()
is virtual, then doing this:
const Base *base = this;
base->foo();
or equivalently:
static_cast<const Base*>(this)->foo();
will not call Base::foo()
but Derived::foo()
. That's what virtual functions do. If you want to call a specific version of a virtual function you just specify which one:
this->Base::foo(); // non-virtual call to a virtual function
Naturally, the this->
part is not really necessary:
Base::foo();
will work just fine, but some people prefer to add the this->
because the latter looks like a call to a static function (I have no preference on this matter).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With