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.

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Cosmo
Зарегистрируйся сейчас
или Подпишись на будущие тесты