Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ how to call method in derived class from base class

What I want to do is for Execute() to run and completes it calls the Base::Done() then calls the Derived::Done(). I'm doing this because Base class Execute will do something and when its done call the Derived::Done(). I hope I'm explaining it correctly. Kind of like a listener that is called when a task completed. I'm kinda stuck on how the Base class will call the Derived class.

class Base
{
  virtual void Done(int code){};
  void Execute();
}

void Base::Execute()
{
}


class Derived : Base
{
  void Done(int code);
  void Run();
}

Derived::Done(int code)
{
}

void Derived::Run()
{
    Execute();
}
like image 272
adviner Avatar asked Jun 26 '13 15:06

adviner


1 Answers

You can use a template method:

class Base
{
 public:
  void Execute()
  {
    BaseDone(42);
    DoDone(42);
  }
 private:
  void BaseDone(int code){};
  virtual void DoDone(int) = 0;
};

class Derived : Base
{
 public:
  void Run() { Execute(); }
 private:
  void DoDone(int code) { .... }
};

Here, Base controls how its own and derived methods are used in Execute(), and the derived types only have to implement one component of that implementation via a private virtual method DoDone().

like image 129
juanchopanza Avatar answered Sep 23 '22 11:09

juanchopanza