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!
It will print
A::print()becausea=bcauses object-slicing, which meansagets only the a-subobject ofb. Read this :Note that runtime-polymorphism can be achieved only through pointer and reference types. In the above code,
ais neither pointer, nor reference type: