About C + + polymorphism

Source: Internet
Author: User

Recommended "Inside the C + + Object Model", the article is transferred from one paragraph.

Polymorphism is an important feature of object-oriented, and the polymorphism in C + + is realized by virtual function mechanism, and some basic knowledge about C + + polymorphism implementation is not described in detail.

It usually looks like this:

Shape * ps = new Circle;

Ps->rotate (); The call is a virtual function

Although PS is a shape-type pointer, it is called the Rotate method in circle. There is no doubt that doing so will be easy to encapsulate in our program. The main use of polymorphism is to influence the encapsulation of types through a common interface, which is usually defined in an abstract base class. A pointer, no matter what type of data it is on our machine, the amount of memory he needs is fixed, like a 16-bit machine on a 2byte,32-bit machine is 4byte, and we use pointers to call object functions, members, because we know the size of the area that this type of object occupies in memory, You can naturally find the member address and virtual function list pointer through the pointer. As an example, here's a zooanimal statement:

Class Zooanimal {

Public

Zooanimal ();

Virtual ~zooanimal ();

//...

virtual void rotate ();

Protected

int Loc;

String name;

};

Zooanimal za ("Zoey");

Zooanimal *pza = & za;

Where class object za and pointer pza are possible layouts are as follows:

  

But how does a pointer to zooanimal differ from a pointer to an integer or a template Array (as follows, with a string)?

Zooanimal * PX;

int *pi;

Array<string> * PTA;

In terms of memory requirements, nothing is different! All three of them need enough memory to hold a machine address (32 bits for 4 bytes). The difference between "pointers to different types" is not the same as its pointer notation, nor its content (representing an address), but rather the type of object it addresses. In other words, the pointer type tells the compiler how to interpret the memory content and its size in a particular address:

Well, then, a pointer to address 1000 and type void*, what address space will be covered? Yes, we don't know! This is why a pointer of type void can contain only one address and cannot manipulate the object it refers to.

So, transformation (cast) is actually a compiler directive, and most of the time he does not change the real address of a pointer, it only affects the "size and content of the indicated memory" and the way it is interpreted.

Now, let's define a bear as a zooanimal. Of course, this task can be accomplished through "public inheritance":

Class Bear:public zooanimal{

Public:

Bear ();

~bear ();

//..

void rotate ();

virtual void dance ();

Protected

Enum dances{...};

Dances Dances_known;

int cell_block;

}

Bear B ("Yogi");

Bear *PB = &b;

Bear &rb = *PB;

B, Pb, RB what kind of memory requirements? Either pointer or reference requires only 4 bytes (16-bit 2-bytes) space. The Bear object requires 24bytes, which is Zooanimal 16bytes plus the 8bytes brought by the bear, which shows the possible memory layout:

    

Well, suppose our bear object is placed at 1000 of the address, what is the difference between a bear pointer and a zooanimal pointer?

Bear B;

Zooanimal *pz = &b;

Bear * PB = &b;

Each of them points to the first byte of a Bear object. In the meantime, PB covers an address that contains the entire bear object, while the address contained in the PZ contains only the Zooanimal subobject in the.

In addition to the members appearing in Zooanimal subobject, you cannot use PZ to directly dispose of any members of the bear. The only column outside is through the virtual mechanism:

Illegal: Cell_block is not a member of Zooanimal

Although we know that PZ is currently pointing to the Moth bear Object.

pz->cell_block;

OK: After a clear downcast operation, no problem.

((bear*) PZ)->cell_block;

The following is better, but it is a run-time operation (higher cost)

if (bear* PB2 = dynamic_cast<bear*> (PZ))

pb2->cell_block;

Ok, because Cell_block is a member of Bear.

pb->cell_block;

When we write:

Pz->rotate ();

, the type of PZ will determine the following two points at compile time

1) Fixed available interface. In other words, PZ can only invoke the public interface of Zooanimal

2) access level for this interface (columns such as rotate () is a public member of Zooanimal)

At each execution point, the type of object that PZ refers to determines the entity that the rotate () invokes. The encapsulation of type information is not maintained in the PZ, but in the maintenance and link, the link exists between "Object Vptr" and "vitual table".

Now, take a look at this situation:

Bear B;

Zooanima za = b; This will cause cutting (sliced)

Call Zooanimal::rotate ()

Za.rotate ();

Why does rotate () call a zooanimal entity instead of a bear entity? In addition, if the initialization function (when the application and the number of rows assignment operation occurs) copies an object content to another object, why does Za's VTR not point to the Bear's virtual table?

The answer to the second question is that the compiler makes a quorum between (1) initializing (2) The specified (Assignment) operation (Assigning a class object to another class object). The compiler must ensure that if an object contains one or more vptrs, the content that writes Vptrs is not initialized or changed by the base class object.

The answer to the first question is: Za is not (and will never be) a bear, it is (and can only be) a zooanimal. Polymorphism caused by the "more than one type" of potential power, and can not actually play in the "Direct access to objects" this matter. There is a specious notion that OO programming does not support direct processing of object. For example, the following set of definitions:

{

Note: Panda inherit bear and bear inherit Zooanimal

Zooanimal za;

Zooanimal *pza;

      

Bear B;

Panda *pp =new Panda;

Pza = &b;

}

Its possible memory layouts are as follows:

 

It is clearly not a problem to assign the address of za or b, or the content (also an address) contained in PP, to Pza. One pointer or one reference supports multiple units because they do not raise any "type-related memory delegate operations (Type-dependent Commitment)" in memory; they are changed only by the memory they point to. Size and the way content is interpreted. "

However, if anyone changes the size of object za (or is designated as) a derived class object, derived object will be cut to fit into the smaller base type memory, derived type will leave no trace. Polymorphism is no longer present, and a strict compiler can then parse a "virtual function call operation triggered by this object", thus avoiding the virtual mechanism. If virtual function is defined on the Russian-Japanese inline, it is more efficient.

In summary, polymorphism is a powerful design mechanism that allows you to encapsulate related types after you inherit an abstract public interface. The cost, however, is the extra indirection-whether in "Memory acquisition" or "type determination". C + + uses class pointer and references to support polymorphism, which is "object-oriented."

  

About C + + polymorphism

Related Article

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.