Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

c++ - Calling overriden (derived class) version of a non-virtual base class function from inside base class?

So, if I have

class base
{
  public:
  virtual void start();
  virtual void stop();

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

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

calling derived.doSomething() will call derived::start() and derived::stop().
BUT this only works if they're virtual.

I wanted to know why it doesn't work without the virtual keyword, meaning the lower level details. I can't find much about this online...

Thanks!

question from:https://stackoverflow.com/questions/66050562/calling-overriden-derived-class-version-of-a-non-virtual-base-class-function-f

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Without the virtual keyword, base::doSomething code has NO IDEA about the derived version's of those methods (think linker resolution)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...