Understanding inheritance and polymorphism in C ++

Suppose we have the following inheritance classes.

class A
{
public:
    void virtual show()
    {
        cout << "I am A\n";
    }
};

class B:public A
{
public:
    void show()
    {
        cout << "I am B\n";
    }
};

class C:public B
{
public:
    void show()
    {
        cout << "I am C\n";
    }
};

int main()
{
    A *obj = new C();
    obj->show();

    return 0;
}

Without creating any other object, how can I call a function of class B (),

One way I know is to change show () in class C to,

void show()
{
    B::show();
    cout << "I am c\n";
}

This will first call display function B, then print "I am." But I do not want show () in C to be executed at all. I want B show () to be executed directly.

Is it possible? Can we do this using casting or something else?

Remember that I am not allowed to create any other object than the already created ie C in main (). I was asked this question at an interview today.

Thank!

+4
source share
1 answer

:

int main()
{
    A *obj = new C();
    static_cast<B*>(obj)->B::show();

    return 0;
}

, , B, undefined.

+7

Source: https://habr.com/ru/post/1694255/


All Articles