To use C ++ polymorphism, you need to use pointers as much as possible, instead of objects. C ++ is inconsistent when processing the two. During function transfer, the base class may mask the type of the inherited class, thus losing the polymorphism.
Class Base
{
Public :
Virtual Void Print ()
{
Cout<"Base"<Endl;
}
} ;
Class Suba: Public Base
{
Public :
Void Print ()
{
Cout<"Suba"<Endl;
}
} ;
Class Subb: Public Base
{< br> Public :< br> void Print ()
{< br> cout " subb \ n " ;< BR >}
} ;
Class Super
{
Private :
Base A1; // Object
Base * A2; // Pointer
Public :
Super (Base & A, base * B)
{
A1=A;
A2=B;
}
Void Print1 ()
{
A1.print ();
}
Void Print2 ()
{
A2->Print ();
}
} ;
Int Main ()
{
Base B;
Suba SA;
Subb Sb;
Super S1 (B,&B );
S1.print1 ();
S1.print2 ();
Super S2 (SA,&SB );
S2.print1 ();
S2.print2 ();
}
/**/ /*********************************
Base
Base
Base
Subb
*********************************/
The above results show that
It is also a base subclass. the type of the object used is overwritten by the base class, and there is no problem in using pointers.
I think it is caused by class assignment during Super construction.
Assignment and copying constructors often produce unexpected sub-effects, while pointers do not.
When using STL containers, try to use pointers for storage, unless you are only interested in values.