Есть ли разница между объявлением унаследованной виртуальной функции в дочернем классе с ключевым словом "virtual" или без , учитывая, что я хочу назвать fun соответствующим типу моих объектов.Посмотрите на комментарии.
#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;
}