Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding inheritence and polymorphism in C++

Suppose we have following inherit 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 B class's show() function???

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

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

This will first call B's show function then it will print "I am C". But I don't want the show() in C to be executed at all. I want the B's show() to be executed directly.

Is it even possible? Can we do it using casting or something?

Remember I am not allowed to create any other object other then the one already created i.e. C in main(). I was asked this question at an interview today.

Thanks!

like image 249
Muzahir Hussain Avatar asked Mar 06 '23 18:03

Muzahir Hussain


1 Answers

You can force static dispatching by specify the class:

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

    return 0;
}

But if you want to use this method, you must be sure that the object is indeed a B instance, otherwise it's undefined behavior.

like image 67
llllllllll Avatar answered Mar 16 '23 00:03

llllllllll