If I derive B from A and C from B like so:
A
|
B
|
C
Most likely I will have one or more virtual functions in A. Now, accidently I forgot to put the keyword virtual in B's function declaration. But to my surprise it works as if virtual was set also in B. This is the code:
#include <iostream>
using std::cout;
using std::endl;
class A
{
public:
virtual void foo(){cout << "A\n";};
};
class B : public A
{
public:
void foo(){cout << "B\n";} // a "virtual doesn't change the behaviour...
};
class C : public B
{
public:
void foo(){cout << "C\n";}
};
int main()
{
C c;
c.foo();
A *pa = new C;
pa->foo();
B *pb = new C;
pb->foo();
return 0;
}
If you omit also the virtual in A, the output is
C
A
B
Otherwise it is
C
C
C
even without the virtual in B!
So: Is the keyword pinherited in some way? Or do I understand something wrong here?
If a method is virtual in a base class, then it is virtual in its subclasses, without them having to declare it as such.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With