Virtual function keyword

时光总嘲笑我的痴心妄想 提交于 2019-12-02 09:33:17

问题


Is there any difference between declaring inherited virtual function in a child class with the "virtual" keyword or not, considering I want to call fun appropriate to my objects' type. Look at the comments.

#include <cstdio>
struct A{
    int a;
    A():a(5){}
    virtual int fun(){return a+1;}
};
struct B: public A{
    virtual int fun(){return a+5;} //I put virtual here
//  int fun(){return a+5;} // Any difference if I put virtual before or not?
};
int main(){
    B obj;
    printf("%d\n", static_cast<A>(obj).fun()); // A::fun() called. Why?
    printf("%d\n", static_cast<A&>(obj).fun()); // B::fun() called. As expected
    printf("%d\n", static_cast<A*>(&obj)->fun()); // B::fun() called. As expected
    printf("%d\n", static_cast<A>(B()).fun()); // A::fun() again. Why?
//  printf("%d\n", static_cast<A&>(B()).fun()); //invalid_cast error. Why? 
    printf("%d\n", static_cast<A*>(&B())->fun()); //It works! B::fun() call
    return 0;
}

回答1:


Overriding functions in derived classes are implicitly declared "virtual" if the corresponding function in the base class is virtual. Just make sure you got the exact same signature, or you might inadvertently hide the original function and declare a new one!

In C++0x, feel free to make liberal use of the override specifier.

Your two "Why?" questions are because of slicing; you're making new, copy-sliced objects of type A. Note that in B x; static_cast<A>(x); the cast is the same as saying A(x).




回答2:


Keeping the virtual key word before the overridden member function in the derived class is optional. Run-time polymorphism works only for pointers or references.



来源:https://stackoverflow.com/questions/7054180/virtual-function-keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!