0

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?

Tony The Lion
  • 61,704
  • 67
  • 242
  • 415

3 Answers3

6

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.

sbi
  • 219,715
  • 46
  • 258
  • 445
  • but DoSomething is important though, not sure if you left it out for brevity or because it's wrong that's there? – Tony The Lion Apr 18 '11 at 09:12
  • I hadn't seen the implementation of `Base::Execute`. +1 to you, the problem is even more trivial than I thought. – Fred Foo Apr 18 '11 at 09:13
  • 1
    @Tony: `DoSomething` isn't relevant to your problem since it doesn't follow the NVI principle at all. – Fred Foo Apr 18 '11 at 09:14
  • 1
    @Tony: As far as I can see, it's not used in the example, so I cut it out. But the code still links even if you put it back in (provided you also put in an implementation). – sbi Apr 18 '11 at 09:14
  • So, why do you include ? – rjnilsson Apr 18 '11 at 09:17
  • @Tony: Try to copy and paste the exact solution from the answer into a single file, it should work. – rjnilsson Apr 18 '11 at 10:19
  • @Cwan: Good catch. It's part of my test cpp file, and I didn't remove it. – sbi Apr 18 '11 at 22:07
  • @Tony: If this doesn't compile for you, your compiler is so seriously broken, I doubt you can do anything useful with it. – sbi Apr 18 '11 at 22:11
0

You should probably also make exec_() pure virtual in your base class. You then also need to implement it in your derived classes.

DanDan
  • 10,462
  • 8
  • 53
  • 69
0

You need to write a function definition for exec_() function.

Umesha MS
  • 2,861
  • 8
  • 41
  • 60