3
votes

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;
}
2

2 Answers

8
votes

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

3
votes

To call a base class function that you are overriding you call Base::Fun(...).

You do the following Base::foo(), here is a full code sample:

class Base
{
public:
    virtual double  foo() const
    {
        return 5;
    };
};

class Derived : Base
{
    int s;

public:

    Derived() : s(5)
    {
    }

    virtual double  foo() const
    {
        // s is a variable only associated with Derived
        double x;

        //NOTE THE Base::foo() call
        x = s + Base::foo(); // this is the line i dont know what im doing?!
        return x;
    }
};