In the below c++ code using virtual functions
#include<iostream>
using namespace std;
class Base{
public:
virtual void fun(){
cout << "Base::fun()called \n";
}
};
class Child : public Base {
public:
void fun() {
cout << "Child::fun() called\n";
}
void door(){
cout << "Child::door() called \n";
}
};
int main(){
Base *base_ptr = new Child();
base_ptr->fun();
return 0;
}
How can I invoke door function using base_ptr? This question was asked in an interview. I was wondering whether it can be possible
Thanks for your replies
(Assuming that Base
and Child
cannot be modified.)
You can use static_cast
to convert base_ptr
to Child*
.
static_cast<Child*>(base_ptr)->door()
This is safe as long as you are sure that base_ptr
is actually pointing to a Child
instance.
If you don't know what derived instance type base_ptr
is pointing to, consider using dynamic_cast
:
if(auto child = dynamic_cast<Child*>(base_ptr))
{
child->door();
}
Unless the compiler manages to aggressively optimize it, dynamic_cast
has extra runtime overhead compared to static_cast
.
Because Base
has no door()
method, you obviously cannot simply call base_ptr->door()
.
However, if you know base_ptr
is a Child
, you can cast it and then call door()
Child* child_ptr = static_cast<Child*>(base_ptr);
child_ptr->door();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.