c++polymorphismvirtualnon-virtual-interface

Non-Virtual Interface - how to invoke the correct virtual function


I have a hierarchy that looks something like this:

class Base
{
public:
    void Execute();
    virtual void DoSomething() = 0;
private:
    virtual void exec_();
};

class Derived : public Base
{
public:
   //DoSomething is implementation specific for classes Derived from Base
   void DoSomething();

private:
    void exec_();
};

void Base::Execute()
{
    // do some work 
    exec_();  //work specific for derived impl
    // do some other work
}

void Derived::DoSomething()
{
   //impl dependent so it can only be virtual in Base
}


int main()
{
  Derived d;
  Base& b = d;

  b.Execute();  //linker error cause Derived has no Execute() function??

}

So the question is how do I call Execute() using this pattern when I create a derived using my Base class. In my case I do not want to create Derived directly, as I have multiple classes derived from Base and depending on some condition I have to pick a different derived class.

can anyone help?


Solution

  • This

    class Base
    {
    public:
        void Execute();
    private:
        virtual void exec_() {}
    };
    
    class Derived : public Base
    {
    private:
        void exec_() {}
    };
    
    void Base::Execute()
    {
        // do some work 
        exec_();  //work specific for derived impl
        // do some other work
    }
    
    int main()
    {
        Derived d;
        Base& b = d;
    
        b.Execute();
    }
    

    compiles, links, and runs for me.