In C++, is a function automatically virtual if it overrides a virtual function?

Viewed 3708

I would expect that if foo is declared in class D, but not marked virtual, then the following code would call the implementation of foo in D (regardless of the dynamic type of d).

D& d = ...;
d.foo();

However, in the following program, that is not the case. Can anyone explain this? Is a method automatically virtual if it overrides a virtual function?

#include <iostream>

using namespace std;

class C {
public:
        virtual void foo() { cout << "C" << endl; }
};

class D : public C {
public:
        void foo() { cout << "D" << endl; }
};

class E : public D {
public:
        void foo() { cout << "E" << endl; }
};

int main(int argc, char **argv)
{
        E& e = *new E;
        D& d = *static_cast<D*>(&e);
        d.foo();
        return 0;
}

The output of the above program is:

E
4 Answers
Related