Viktor Axén
Viktor Axén

Reputation: 319

How to make a derived class function always call the same base class function when called?

How do I make a base class virtual function so that it always is called when a derived class calls its version of the function? I know I can call the base classes function by writing something like BaseClass::foo() at the beginning of the the function DerivedClass::foo(), but what if I want it to be called by default, without the creator of the derived class even knowing that the base classes function does anything?

class BaseClass
{
     BaseClass();
     virtual void foo() {
         printf("base");
     }
}

class DerivedClass : public BaseClass
{
    DerivedClass();
    void foo() {
        printf("derived");
    }
}

int main()
{
     DerivedClass dc;
     dc.foo();
}

Should print:

base
derived

Upvotes: 2

Views: 452

Answers (1)

Lukas-T
Lukas-T

Reputation: 11340

That's not directly possible. You could split the function in non-virtual foo on the base class and (pure) virtual fooCore on the derived classes:

class Base {
  protected:
    virtual void fooCore() = 0;
  public:
    void foo(){
      // do stuff, then call method of derived class
      this->fooCore();
    }
};

class Derived {
  protected:
    void fooCore() override { 
        //actual 
    };
};

From the "outside" the call Base::foo() stays the same.

Upvotes: 2

Related Questions