A small analysis of C + + polymorphism

Source: Internet
Author: User

The polymorphism of C + + can be divided into two types:

1. Compile-time polymorphism: operator overloading and function overloading. This is relatively simple, a brief introduction, the focus is the runtime polymorphism.

Operator overloading mainly uses the operator keyword of C + + to redefine the operator:

classtest{intb; Public: Test (); Test (intAintb); void operator>> (Test &);}; Test::test () {a=b=1;} Test::test (intAintb) {         This->a=A;  This->b=b;}voidTest::operator>> (Test &p) {cout<<p.a<<" "<<p.b<<Endl;}intMain () {Test cout (1,2), B; cout>>b; return 0;}

Function overloading: One thing to keep in mind: only a redefinition function with a different return value is wrong, and not much else is said.

2. Run-time polymorphism: One of the virtual base class tables can be said to be mainly from the processing of inheritance of the inverted parallelogram problem (to apply others words ...) ), that is, a base class has multiple subclass inheritance, and many subclasses are inherited only by one grandchild class. As an example:

class Base{ Public:    intA;};classD1: Public Base{ Public:    intb;};classD2: Public Base{ Public:    intc;};classD3: PublicD1, Publicd2{ Public:    intsum;};intMain () {D3 _d3; _D3.A=Ten; _d3.b= -; _D3.C= -; _d3.sum= _d3.a + _d3.b + _d3.c;//Errorcout << _d3.sum <<Endl;} 

Note the error is because _d3.a is not clear, because it may be d1,d2 or D3, then to solve this problem, there are two ways:

The first is to indicate the scope is _d3.d1::a, this method is relatively simple and basic does not need, no longer repeat

The second is to use the virtual keyword to keep multiple classes of inheritance only a copy of the base class (emphasis!!) )

class Base{ Public:    intA;};classD1:Virtual  Public Base{ Public:    intb;};classD2:Virtual  Public Base{ Public:    intc;};classD3: Public Base{ Public:    intD;};classD4: PublicD1, Publicd2{ Public:    intsum;};intMain () {D4 _d4; _d4.a=Ten; _d4.b= -; _D4.C= -; _d4.sum= _d4.a + _d4.b +_d4.c; cout<< _d4.sum << Endl;//correctcout<<sizeof(D1) <<" "<<sizeof(D2) <<" "<<sizeof(D3) << Endl;//Output Results 8    return 0;}

By adding the virtual keyword in the process of inheritance, the description is a virtual base class, in which the virtual base class will only retain an identical class member when multiple inheritance occurs, thus fundamentally solving the inverted parallelogram effect!

In addition to the last output, it can be seen that there is no addition to the virtual keyword of the analogy added 4 less bytes. What is the reason for this, through disassembly can look:

It can be seen that each class has a virtual base class table as the object's data members are saved, so the above program execution will be 4 bytes more.

The second virtual function (which can be said to be the main content of the operation polymorphism): virtual function and function overloaded form very much like, but is not a thing, virtual function must ensure that the function name, parameters are exactly the same, but the function body is not the same.

Virtual functions (virtual function) are implemented by a virtual function table (virtual table), that is, virtual tables. Referred to as v-table. In this table, the master is the Address table of the virtual function of a class, which solves the problem of inheritance, overwriting, and guarantees the actual function of the real response. Thus, in an instance of a class with virtual functions, the table is assigned to the memory of this instance, so when we manipulate a subclass with a pointer to the parent class, the virtual function table is important, and it is like a map that indicates the function that should actually be called.

An example is given to analyze:

classtest{ Public:    Virtual voidVfunc () {cout <<"base ' s Vfunc"<<Endl;}};classD1: Publictest{ Public:    voidVfunc () {cout <<"D1 ' s vfunc!"<<Endl;}};classD2: Publictest{ Public:    voidVfunc () {cout <<"D2 ' s vfunc!"<<Endl;}};intMain () {_asm {int 3    }//for debuggingTest A, *p;    D1 B;    D2 C; P= &A; P-Vfunc (); P= &b; P-Vfunc (); P= &C; P-Vfunc (); return 0;}
CPU disasm address hex data Directive Comment0101273ECC Int30101273F8D4D F8LeaECX, [ebp-8];This pointer a01012742E8 40e9ffff               PagerDemo.01011087               ;test::test010127478D4D E0LeaECX, [ebp- -];This pointer b0101274AE8 9FEBFFFFPagerDemo.010112EE               ;D1::d 10101274F8D4D D4LeaECX, [ebp-2c];This pointer c01012752E8 96ECFFFFPagerDemo.010113ED               ;D2::d 2010127578D45 F8LeaEAX, [ebp-8];the address of object A is saved to eax0101275A              8945ECmovDWORD ptr [ebp- -], eax;Save object A With object pointer p0101275D8b45 ECmovEAX, DWORD ptr [ebp- -];sets the current this pointer to object A.010127608b10movedx, DWORD ptr [EAX];virtual table ' vftable010127628bf4movESI, esp010127648B4D ECmovECX, DWORD ptr [ebp- -]010127678b02moveax, DWORD ptr [edx]01012769FFD0Pagereax

As can be seen from disassembly, the call virtual function is mainly through the this pointer to distinguish between different functions, and the virtual table in the object data header.

Here's a look at the vftable virtual table data structure:

Simply put, the virtual table in the subclass that inherits the parent class is a two-dimensional array, stealing someone else's diagram and discussing multiple inheritance:

Three parent classes derive a subclass, where the F () function of the subclass overrides the F () function in the parent class, looking at the virtual table structure in the class:

With this diagram we can clearly see that each parent class occupies an array. Repeat the disassembly for this program:

classbase1{ Public:    Virtual voidVfunc () {cout <<"base ' s Vfunc"<<Endl;}};classbase2{ Public:    Virtual voidVfunc () {cout <<"D1 ' s vfunc!"<<Endl;}};classDerive: PublicBASE1, Publicbase2{ Public:    voidVfunc () {cout <<"D2 ' s vfunc!"<<Endl;}};intMain () {_asm {int 3} Derive D;    D.vfunc (); return 0;}

The increment of this linear structure, that is, the increase of the imaginary table, can be seen by eax+4. (This od suddenly collapsed.) Collapse of the inexplicable ... Originally intended to copy over, the results can only be screenshots, there is no way to annotate the analysis ... Excuse me.. )

A small analysis of C + + polymorphism

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.