s*******e 发帖数: 27 | 1 I was asked an iterview question and I was kind of confused at the time.
Please tell me if the following code compiles and why?
Thx.
class base
{
public:
virtual void foo(){}; //virtual
};
class derived : public base
{
public:
void foo(){}; //virtual
void bar(){}; //not a vritual function
};
base* p = new derived;
p->bar(); //will this compile and why before you run it. | z****e 发帖数: 2024 | 2 no, it will not compile, because bar is not virtual and vptr can not lookup the vtable and find it. so it should fail. bar is not even a member of base.
actually, even bar() is virtual but added by Derived, through base class pointer to call it, is a compile time error. you can downcast using
dynamic_cast(p)->bar() to finish the call. | s*******e 发帖数: 27 | 3 Thanks a lot.
lookup the vtable and find it. so it should fail. bar is not even a member
of base.
pointer to call it, is a compile time error. you can downcast using
【在 z****e 的大作中提到】 : no, it will not compile, because bar is not virtual and vptr can not lookup the vtable and find it. so it should fail. bar is not even a member of base. : actually, even bar() is virtual but added by Derived, through base class pointer to call it, is a compile time error. you can downcast using : dynamic_cast(p)->bar() to finish the call.
|
|