Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the keyword "virtual" passed on to intermediate base-classes?

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?

like image 808
steffen Avatar asked Sep 11 '26 07:09

steffen


1 Answers

If a method is virtual in a base class, then it is virtual in its subclasses, without them having to declare it as such.

like image 69
Fred Foo Avatar answered Sep 12 '26 19:09

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!