Calling derived class function from base class

cpp help picture cpp help · Feb 2, 2011 · Viewed 44k times · Source
class base
{
  public:
  virtual void start();
  virtual void stop();

  void doSomething() { start(); .... stop(); }
}

class derived : public base
{
  public:
   void start();
   void stop();
}

But when I call doSomething() in the derived class it is using it's own definition of Start() and Stop() - not the derived ones.

I don't want to rewrite doSomething() in the derived class because it would be identical to the base one. What am I doing wrong?

Sorry if that wasn't clear.
The behaviour of Start() and Stop() in the derived class is different (it's a different machine) - but I want to use the original base class doSomething() because that hasn't changed. It just has to start() and stop() using the new derived class code.

Answer

Rob Kennedy picture Rob Kennedy · Feb 2, 2011

The code you've posted should work the way you want. Calling doSomething on an instance of derived will call the overridden start and stop functions defined in derived.

There's an exception to that, though. If you call doSomething in the constructor or destructor of base (whether directly or indirectly), then the versions of start and stop that get called will be the ones defined in base. That's because in those circumstances, you don't actually have a valid derived instance yet. It's either not fully constructed or partially destructed, so the language prevents you from calling methods that would use the partial object.

If you're not calling it from a base constructor or destructor, then there is more to the problem than what's shown here.