2
#include <iostream>  

class Base  
{  
public: 
    virtual ~Base() {}  
    virtual void f()  
    {  
        std::cout << "base\n";  
    }
};

class Derived : public Base
{  
public:  
    virtual ~Derived() {}  
    virtual void f()    
    {  
        std::cout << "derived\n";  
    }  
};  

int main()  
{  
    Derived* D = new Derived;  
    D->f();
    delete D;  
    return 0;  
}

So I am calling Derived::f but I want to call Base::f too. Is there any other way than calling Base::f() inside Derived::f()?

Ajay
  • 18,086
  • 12
  • 59
  • 105
BoomShh
  • 21
  • 1
  • @PiotrSkotnicki But then it doesn't call Derived::f() – BoomShh Jun 06 '16 at 18:56
  • So you have a flawed design. Why would you need a mechanism that calls both functions, if you can do it yourself? – Piotr Skotnicki Jun 06 '16 at 18:58
  • 1
    Do you want to *always* call `Base::f` whenever you call `Derived::f`? If not, `D->Derived::f(); D->Base::f();`? If so, just call `Base::f` within `Derived::f`. C++ does not suport automatic ctor/dtor style inheritance outside of ctors/dtors. – Yakk - Adam Nevraumont Jun 06 '16 at 18:59
  • Duplicate of: [How to implement an interface class using the non-virtual interface idiom in C++?](http://stackoverflow.com/q/2735563/514235) or [Non-virtual interface design pattern in C#/C++](http://stackoverflow.com/q/6481260/514235). Related: [How to call a parent class function from derived class function?](http://stackoverflow.com/questions/357307/how-to-call-a-parent-class-function-from-derived-class-function) – iammilind Jun 07 '16 at 06:40

1 Answers1

2

Sounds like what you want is a Non Virtual Interface (NVI) design. This is great when you want customization points (polymorphism, for example) for derived classes, but a somewhat guaranteed call flow.

class Base  
{  
public:

    virtual ~Base() {}  

    void f()  
    {
        // ... do something that always run before
        f_impl();
        // ... and after the extension point
    }

protected:

    virtual void f_impl()
    {
    }
};

class Derived : public Base
{  
protected:  

    virtual void f_impl() override
    {
        std::cout << "extended!\n";
    }  
};

int main()  
{  
    Derived d;  
    d.f(); // Base can _always_ run things before and after Derived
}
Johann Gerell
  • 24,991
  • 10
  • 72
  • 122