What will be displayed by ​the following program?
#include <iostream>
using namespace std;

struct A
{
    void foo() { cout << "A::foo()\n"; }
};

struct B : virtual A
{
    virtual void foo() { cout << "B::foo()\n"; }
};

struct C : B, virtual A
{
    void foo() { cout << "C::foo()\n"; }
};

int main (int argc, char *argv[])
{
    C().foo();
    A *a = new C; a->foo();
    static_cast<A*>(new C)->foo();
    return 0;
}
Explanation
Hence function foo() in struct A defined isn't virtual, static binding would be applied to it. That's why function calls from A* pointers would print A::foo to console. If we change A* to B* in main() then dynamic binding would be applied and function C::foo() called.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Cosmo
Sign Up Now
or Subscribe for future quizzes