1

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
Viktor Axén
  • 199
  • 2
  • 11
  • Are you saying that the base function should be called *instead* of the derived function or just *before* the derived one? – sshashank124 Dec 28 '19 at 14:16
  • Please read on how to create a [mcve]. Your question is not clear. Is the derived method also supposed to be called? Are you calling it through a pointer/reference or directly on an object? Code examples are needed. – super Dec 28 '19 at 14:17
  • Sorry for being unclear. I want it to be called before the derived function. Both the base function and the derived function should run. – Viktor Axén Dec 28 '19 at 14:17
  • This cannot be done in C++ automatically, like that. C++ simply doesn't work this way. – Sam Varshavchik Dec 28 '19 at 14:18
  • Does this answer your question? [What are the rules for calling the superclass constructor?](https://stackoverflow.com/questions/120876/what-are-the-rules-for-calling-the-superclass-constructor) – sshashank124 Dec 28 '19 at 14:19
  • 5
    You could have a non-virtual function in your base class, that first does something and then calls a virtual function on itself. – super Dec 28 '19 at 14:19
  • 2
    Why not a public non-virtual method in the base class that performs the required work and then calls a virtual private member? That's fairly standard. – G.M. Dec 28 '19 at 14:20
  • @G.M. That's a valid answer. – Olaf Dietsche Dec 28 '19 at 14:22

1 Answers1

2

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.

Lukas-T
  • 11,133
  • 3
  • 20
  • 30