Coverage of C ++ Polymorphism

Source: Internet
Author: User

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.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.