I have a problem in virtual function: Here is some code as an example:
class A
{
public : virtual void print(void)
{
cout<< "A::print()"<<endl;
}
};
class B : public A
{
public : virtual void print(void)
{
cout<<"B::print()"<<endl;
}
};
class C : public A
{
public : void print(void)
{
cout<<"C::print()"<<endl;
}
};
int main(void)
{
A a,*pa,*pb,*pc;
B b;
C c;
pa=&a;
pb=&b;
pc=&c;
pa->print();
pb->print();
pc->print();
a=b;
a.print();
return 0;
}
the result: A::print() B::print() C::print() A::print()
I know it's a Polymorphism ,and know have a table called virtual-function-table,but I don't know how it is to achieve,And
a=b;
a.print();
the result is: A::print() not B::print(),why it hasn't polymorphism. thank you!
a=b;
a.print();
It will print A::print()
because a=b
causes object-slicing, which means a
gets only the a-subobject of b
. Read this :
Note that runtime-polymorphism can be achieved only through pointer and reference types. In the above code, a
is neither pointer, nor reference type:
A * ptr = &b; //syntax : * on LHS, & on RHS
A & ref = b; //syntax : & on LHS, that is it!
ptr->print(); //will call B::print() (which you've already seen)
ref.print(); //will call B::print() (which you've not seen yet)