0

Let's say I create a class A with a virtual function print for dynamic binding. Should I then use the virtual keyword in the derived class' print function as well? If so, why? because it works without.

#include <iostream>
using namespace std;

class A {
public:
    A() {}
    virtual ~A() {}
    virtual void print() { cout << "A" << endl; }
};

class B : public A {
public:
    B() : A() { }
    void print() { cout << "B" << endl; } // why use the virtual keyword here?
};

int main()
{
    A* a[100];
    a[0] = new A();
    a[1] = new B();

    a[0]->print();
    a[1]->print();


    while (true);
    return 0;
}
snzm
  • 139
  • 1
  • 1
  • 10
  • It's optional, or at least it used to be, C++ has changed so much lately that it might be different now. – john Dec 21 '18 at 20:03
  • 1
    using `override` (C++11) is even better :) – Jarod42 Dec 21 '18 at 20:05
  • @Jarod42 Thank you – snzm Dec 21 '18 at 20:07
  • Strictly speaking, `while (true);` is undefined behavior. https://stackoverflow.com/questions/3592557/optimizing-away-a-while1-in-c0x In practical terms the compiler can assume that your loop will *eventually* finish (even if it provably wont) and since it has no side effects it can be optimized out. – François Andrieux Dec 21 '18 at 20:08
  • I have seen the [duplicate]'s top answer and it is just wrong. `virtual` keyword in class means that you allow to derived classes to completely override this function. If a function is not vitual then it can be inlined and the code doesn't care if it is actually an instance of a derived class. If the function is virtual then its implementation is determined by the final derived class and whenever the function is called, the code needs to dynamically check which function it actually needs to call. Though, I presume there are cases when virtual functions can still be inlined. – ALX23z Dec 21 '18 at 20:57

0 Answers0