0
#include <iostream>

class base {
 public:
 virtual void print(){
  std::cout << "base\n";
 }
};

class dr : public base {
 public:
 void print(){
  std::cout << "dr\n";
 }
};


class last : public dr {
 public:
 void print(){
  std::cout << "last\n";
 }
};

int main(){
 dr *d = new last();
 d->print();
 return 0;
}

In the above code, only the base class includes a virtual function. dr and last do not include a virtual function and yet polymorphism is still working. The output of this code is last. (It should have been dr without polymorphism kicking in).

Does this mean polymorphism works as long as some base class has a virtual function, even though non of the derived classes have one?

Dan
  • 577
  • 1
  • 3
  • 9
  • *dr and last do not include a virtual function* -- Yes they do. – PaulMcKenzie Aug 19 '20 at 15:59
  • Yes Dan, Runtime polymorphism will be applicable if derived class is having a base class with virtual function. Virtual table will be created for all the derived class. – Sanjeev Aug 19 '20 at 16:00
  • If you like to document-in-code that a derived class method is a virtual method being overridden from a base class, you can use `void print() override` where the `override` specifier both ensures that a virtual base class method actually exists, and documents that you intend to override it. – Eljay Aug 19 '20 at 17:50

1 Answers1

2

Both dr::print and last::print override base::print, they're virtual functions too; the keyword virtual is optional here.

(emphasis mine)

Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration) and overrides Base::vf (whether or not the word override is used in its declaration).

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • does this logic also work for "pure virtual"? where `print() = 0` is used? – Dan Aug 19 '20 at 16:01
  • so derived classed that actually define "print" would also be "pure virtual" or just "virtual"? – Dan Aug 19 '20 at 16:05
  • @Dan Just virtual. Pure virtual functions are declared with `= 0` and have no definition. – cdhowie Aug 19 '20 at 16:07
  • @Dan Oh, I got what you meant. It doesn't work for *pure virtual*. If you want the function in derived class be *pure virtual* you have to write `= 0` explicitly. – songyuanyao Aug 19 '20 at 16:08