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.
The code you’ve posted should work the way you want. Calling
doSomethingon an instance ofderivedwill call the overriddenstartandstopfunctions defined inderived.There’s an exception to that, though. If you call
doSomethingin the constructor or destructor ofbase(whether directly or indirectly), then the versions ofstartandstopthat get called will be the ones defined inbase. That’s because in those circumstances, you don’t actually have a validderivedinstance 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
baseconstructor or destructor, then there is more to the problem than what’s shown here.