Calling derived class function from base class

前端 未结 2 729
悲&欢浪女
悲&欢浪女 2020-12-03 05:46
class base
{
  public:
  virtual void start();
  virtual void stop();

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

class derived : public base
{
  public:
   v         


        
2条回答
  •  暖寄归人
    2020-12-03 06:15

    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.

提交回复
热议问题