Why does not agree with the expected structure?

#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();
pa->f();
B *pb=(B*)pa;
pb->f(); //Why not output B?
}

Started by Lorraine at November 20, 2016 - 7:59 AM

Because the f () is virtual ah, pb points to is in fact an instance of A, the output is certainly not B.

Posted by Guy at December 01, 2016 - 8:01 AM

A *pa=new A();
It provides B function cannot be used.

Posted by Ellis at December 04, 2016 - 8:16 AM

What definition of sub class pointer, let he pointed to the superclass object.
This usage is wrong.

Posted by Lillian at December 13, 2016 - 8:48 AM


To understand this you know C++ polymorphism.

Posted by Lulu at December 21, 2016 - 9:07 AM