What is the output of the following code ?
#include <iostream>
using std::cout, std::endl;
class A {
public:
void method() { cout << "A ";}
};
class B: public A {
public:
virtual void method() { cout << "B ";}
};
class C: public B {
public:
void method() { cout << "C ";}
};
int main() {
A* ptr;
A a; B b; C c;
ptr = &a; ptr->method();
ptr = &b; ptr->method();
ptr = &c; ptr->method();
cout << endl;
}
In the class A, method is not defined as virtual, when calling it from a pointer of the class of A (i.e ptr), the compiler has no idea that it should use dynamical binding.
So it does not look at the specific type of the object it points at, either if it is of type B or C, and every times, it calls the method defined in A.
However, if method in class A is defined as virtual, then this aspect is inherited to every other children class, and the output would then be A B C.
This inheritance aspect of virtual is especially true for the C class : its method is virtual, even not explicitly stated, because of B. For instance, the following code :
// ...
class A {
public:
void method() { cout << "A "; }
};
class B: public A {
public:
virtual void method() { cout << "B "; }
};
class C: public B {
public:
void method() { cout << "C "; }
};
class D: public C {
public:
void method() { cout << "D "; }
};
int main() {
C* ptr;
C c; D d;
ptr = &c; ptr->method();
ptr = &d; ptr->method();
cout << endl;
}
outputs ... C D !