Comparison between C ++ and C #: Polymorphism and virtual functions

Source: Internet
Author: User

People on earth know that the three main characteristics of object-oriented are encapsulation, inheritance, and polymorphism. the first two concepts, as the name suggests, are easy to understand. encapsulation means that all the things are encapsulated into classes one by one, and some permission control is provided through access modifiers such as public and private. inheritance means that sub-classes can have non-private member variables and functions of the parent class, just as you can inherit the property of Lao Tzu. the name is not easy to understand, but it is not so easy to understand. in fact, there are other versions of the three features mentioned above, such as data abstraction, inheritance, and dynamic binding. the statement is different, but the meaning is the same.

Polymorphism can be simply understood as there are multiple forms of the same thing, such as rain, snow, and ice are different forms of water. in code, the same function is called, but the function actually performs different operations. the most important way to implement this function is virtual functions. Of course, it is not necessarily necessary to implement this function. The same is true for interfaces. most of the time, however, we still use virtual functions to achieve a little more polymorphism.

 

C # virtual functions and Polymorphism

A virtual function just adds a keyword virtual to the front of a common function. If the virtual function is useless to realize polymorphism, it can be used as a general function, no difference

The following is an example of a father, Father, Son, and daughter.

Class father

{

Public Virtual void showmsg () // This is the virtual function

{

Console. writeline ("this is Father .");

}

}

Class son: Father

{

/* Add override to the end to realize polymorphism. polymorphism means the combination of virtual and override */

Public override void showmsg ()

{

Console. writeline ("this is son .");

}

}

Class daughter: Father

{

/* Override is not used here, but new is used. In fact, new can also be removed, because it is used to add a new one by default. Of course, virtual can also be used, in this way, if anyone inherits this class, they can also achieve polymorphism by working with override */

Public new void showmsg ()

{

Console. writeline ("this is daughter .");

}

}

Test Functions

Public void showyourname (father FA)

{

Fa. showmsg ();

}

 

Static void main (string [] ARGs)

{

Fahter father = new father ();

Father son = new son ();

Father daughter = new daughter ();

Showyourname (father); // The result is this is Father

Showyourname (son); // The result is this is Son

Showyourname (daughter);/* result this is Father. The above two functions reflect polymorphism, but the daughter class does not use override to rewrite the function, so polymorphism cannot be implemented .*/

}

We can see that different operations are performed when the same function showyourname () is called. this is polymorphism. in fact, it is easier to understand the term dynamic binding, that is, the function parameter type fa is only determined at runtime. because subclass is a special parent class, you can use the parent class to replace the subclass type. however, there is no pointer in C # and it is not easy to explain it clearly. It is easier to explain it with pointers when taking the C ++ example.

If you want to use interfaces or abstractions instead of virtual functions, you can also implement polymorphism.

For example, public abstract class father

{

Public abstract void showmsg ();

}

Public interface father

{

Void showmsg ();

}

However, if an inherited abstract function must be rewritten using override, and the new. inherited interface cannot be used, just redefine it like a normal function, but note that the modifier must be public.

In addition, the two cannot be instantiated directly like Father fa = new father (). Other operations will be the same. The same is true for polymorphism.

 

 

C ++ virtual functions and Polymorphism

Assume that there is a parent class father and a subclass son and duaghter.

Class father

{

Public:

Int age;

Virtual void showmsg () {cout <"this is Father." ;}// virtual must have

};

Class son: Public father

{

Public:

Virtual void showmsg () {cout <"this is son." ;}// virtual keywords are optional

};

Class daughter: Public father

{

Public:

Void showmsg () {cout <"this is daughter." <Endl ;}

};

Void showyourname (father * Fa)

{

Fa-> showmsg ();

}

Int _ tmain (INT argc, _ tchar * argv [])

{

Father fa;

Son son;

Daughter Da;

Father * PFA;

PFA = & fa;

Showyourname (PFA); // The result is this is Father

PFA = & Son;

Showyourname (PFA); // The result is this is Son

PFA = & Da;

Showyourname (PFA); // The result is this is daughter

Return 0;

}

 

It seems that C ++ does not use the new keyword like C # To Hide subclass functions. However, there is an operation that can implement similar functions.

In this case, Father * PFA; daughter Da;

PFA = & (father) Da );

Showyourname (PFA); // The result is this is father, which is different from the above example. The above example is this is daughter.

 

How c ++ virtual functions implement Polymorphism

After reading the example, why does a virtual function realize polymorphism in the cloud?

This involves the virtual function table (vtable)

We want to figure out how the three classes Father, Son, and daughter are represented in memory.

FatherIn the memory. you can use sizeof (FA) to check and find that the result is 8. Four bytes are used to hold int-type data, and four other bytes contain a pointer vptr, if the 64-bit pointer is 8 bytes.

Vptr points to a virtual function table with another pointer (* showmsg) () pointing to Father: showmsg (). (This is where the function is actually saved. (if it is not a virtual function, but a general function is also saved in this area, it is not found through pointers ).

Son-likeInherit from Father, so we will copy the stuff in Father memory, so sizeof is also 8. four bytes are saved as int type. the 4-byte storage pointer vptr also points to the virtual function table, but this operation will be performed here. if a virtual function is overwritten in son, the table is updated. Otherwise, the table is not updated. because son overrides the virtual function, the content pointed to by the pointer (* showmsg) () in the table has changed, pointing to Son: showmsg ()

DaughterThe operation is exactly the same as that of son.

 

In this case, when PFA = & Da; indicates that the Pointer Points to the memory of the class daughter, because the corresponding function in the virtual function list is daughter: showmsg (). so I understand why PFA-> showmsg (); this function is called in the daughter class. however, if daughter does not rewrite the virtual function, the entire class of daughter is null, but inherits father. In this case, the function referred to in its virtual function table is father: showmsg ().

 

Now, how does a virtual function realize polymorphism? What is the operation of hiding subclass functions with the new keyword in C # mentioned above?

Father * PFA; daughter Da;

PFA = & (father) Da); // note that the Father da actually completely copies the content in the father-like memory during type conversion. therefore, the function pointed to by the virtual function list is FATHER: showmsg ().

Showyourname (PFA );

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.