简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM