Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access base class object from derived class

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;
}
like image 425
DotSlashSlash Avatar asked Dec 11 '22 00:12

DotSlashSlash


1 Answers

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

like image 62
rodrigo Avatar answered Dec 29 '22 07:12

rodrigo