Here are 2 codes first:
#include<iostream>
using namespace std;
class A{
public:
virtual void f()
{
cout<<"A"<<endl;
}
};
class B: public A{
public:
virtual void f()
{
cout<<"B"<<endl;
}
};
int main()
{
A* pa=new A();
B* pb=new B();
A* upCastpa= static_cast<A*>(pb);
B* downCastpb=static_cast<B*>(pa);
upCastpa->f();
downCastpb->f();
return 1;
}
one display
B
A
Therefore I think what really matters is the objected the pointer pointing to. However, if I remove virtual form A::f(), like this;
#include<iostream>
using namespace std;
class A{
public:
void f()
{
cout<<"A"<<endl;
}
};
class B: public A{
public:
virtual void f()
{
cout<<"B"<<endl;
}
};
int main()
{
A* pa=new A();
B* pb=new B();
A* upCastpa= static_cast<A*>(pb);
B* downCastpb=static_cast<B*>(pa);
upCastpa->f();
downCastpb->f();
return 1;
}
The code will displayed A "stop" What happened? If the important thing is the objected the pointer pointing to.
it suppose to display A B instead of corrupted.
what happened?
I really appreciate any advice or instruction. Thanks a lot.