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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With