Virtual functions in C + +

Source: Internet
Author: User

While it is difficult to find a C + + book or magazine that does not discuss polymorphism, most such discussions make polymorphism and the use of C + + virtual functions seem difficult. I intend to make the reader understand the virtual function implementation technique in C + + from several aspects and combining some examples in this article. Note, write this article just want to communicate with you learning experience because I learned shallow, inevitably there are some errors and shortcomings, I hope you criticize and correct, in this deep gratitude!

In a class, if there is nothing, the class consumes 1 bytes, and once there are other space-occupying members in the class, the 1 bytes are not counted, such as a class with only one int that takes 4 bytes instead of 5 bytes.

If there is only a member function, it is still only 1 bytes, because the class function takes no space

virtual function Because there is a virtual function table, requires 4 bytes, the data member object if the pointer is 4 bytes, note that there is byte alignment, if it is 13 bytes, it is rounded up to 16 bytes of space.

First, the basic concept

First, C + + uses virtual functions to achieve polymorphism. " Regardless of the class of the object that sent the message, they send a message of the same form, and the processing of the message may vary with the object that took over the message, which is known as polymorphism. "In a hierarchical construct of a class built on a base class, you can call a procedure of the same name in an object of any derived class, and the process provided by the invoked procedure can change with the class to which it belongs." A virtual function is first a member function that can be redefined in a derived class of that class and given another processing capability.

Second, definition of virtual function and redefinition in derived class

class class Name {public:virtual class name : base class Name { public : Virtual member function description;}

Third, the structure of virtual function in memory

1. Let's look at an example first:

#include"iostream.h"#include"string.h" classA { Public:Virtual voidFun0 () {cout <<"A::fun0"<<Endl;}}; intMainintargcChar*argv[]) {A A;cout<<"Size of A ="<<sizeof(a) <<Endl;return 0;}
The result is as follows: Size of A = 4

2. If you add another virtual function: virtual void fun1 () {cout << "a::fun" << Endl;}

Get the same results. If you remove the virtual modifier in front of the function

 class   A { public  :  void  fun0 () {cout <<  " a::fun0   << Endl;};  int  Main (int  argc, char  * argv[]) {A a;cout  <<  "  size of A =   " << sizeof  (a) << Endl;  return  0  ;}  
The result is as follows: Size of A = 1

3. Look at the following results:

classA { Public:Virtual voidFun0 () {cout <<"A::fun0"<<Endl;}intA;intb;};intMainintargcChar*argv[]) {A A;cout<<"Size of A ="<<sizeof(a) <<Endl;return 0;}
The result is as follows: Size of A = 12

In fact, the virtual function in the memory structure is this:

Figure A

Under window2000, the pointer occupies 4 bytes in memory, and the virtual function stores the function address in a virtual function table (VTABLE). Look at the example below.

classA { Public:Virtual voidFun0 () {cout <<"A::fun0"<<Endl;}Virtual voidFun1 () {cout <<"a::fun1"<<Endl;}intA;intb;};intMainintargcChar*argv[]) {A A;cout<<"Size of A ="<<sizeof(a) <<Endl;return 0;}

The results are as follows:

Size of A = 4

The memory structure of the virtual function is as follows, you can also find the virtual function table (VTABLE) through the function pointer, and then access each function address to verify this structure, in the foreign site author is: Zeeshan Amjad wrote "ATL on the hood in detail"

Figure II

4. Let's take a look at the memory structure of the virtual function in the inheritance, let's look at the following example

classA { Public:Virtual voidf () {}};classB { Public:Virtual voidf () {}};classC { Public:Virtual voidf () {}};classDrive: PublicA PublicB PublicC {};intMain () {drive D;cout<<"Size is ="<<sizeof(d) <<Endl;return 0;}

The results are as follows: Size is = 12, I believe you can see the following structure diagram will be very clear,

Might

5. Let's take a look at the use of virtual functions to achieve polymorphism, first look at an example:

classA { Public:Virtual voidF () {cout <<"A::f"<<Endl;}};classD | Publica{ Public:Virtual voidF () {cout <<"B::f"<<Endl;}};classE | PublicA { Public:Virtual voidF () {cout <<"C::f"<<Endl;}};classDrive: PublicC { Public:Virtual voidF () {cout <<"D::f"<<Endl;}};intMainintargcChar*argv[]) {A A; b b; C c;drive d;a.f (); B.f (); c.f ();d. f ();return 0;}

结果:A::f B::f C::f D::f

Do not explain, I believe you can see what the truth! Note: Polymorphism is not a function overload

6. Implementing dynamic connections with virtual functions during compilation, the C + + compiler determines that the program uses that function according to the parameter or function return type passed by the program to the function, and then the compiler replaces each boot with the correct function. This compiler-based substitution is called a static connection, and they are executed before the program runs. On the other hand, when a program performs polymorphism, the substitution is performed during the program execution period, and this runtime substitution is called a dynamic connection. Here's an example:

classa{ Public:Virtual voidF () {cout < <"A::f"< <Endl;};}; classB: Publica{ Public:Virtual voidF () {cout < <"B::f"< <Endl;};} ;classC: Publica{ Public:Virtual voidF () {cout < <"C::f"< <Endl;};} ;voidTest (A *a) {a-f ();};intMainintargcChar*argv[]) {B*b=NewB; C*c=NewC;Charchoice; Do{cout< <"type B for Class B,c for class C:"< <endl;cin>>choice;if(choice=="'B"') test (b);Else if(choice=="'C"') test (c);} while(1); cout< < endl< <Endl;return 0;}

In the example above, if you remove the virtual modifier from the class a,b,c, look at the printed result, and then look at the following example to see the relationship between the two. What happens if the virtual modifier in B and C is removed, and the result is not removed.

7. Call the function of the inheriting class in the base class (if this function is a virtual function)

Let's look at an example:

classA { Public:Virtual voidFun () {cout<<"A::fun"<<Endl;}voidShow () {Fun ();}}; classD | PublicA { Public:Virtual voidFun () {cout<<"B::fun"<<Endl;}}; intMain () {A a;a.show ();return 0;}

Print Result: A::fun

In the example in 6, test (a *a) actually has a process of implicitly converting an inherited class pointer to a base-class pointer. We can see that we can invoke the inherited class function in the base class with virtual functions. However, if it is not a virtual function, only the base class function can be called after the inheriting class pointer is converted to a base class pointer. Conversely, if a base-class pointer transforms into a pointer to an inherited class, this can only be a display conversion, and the transformed inherited class pointer can call the base class and inherit the class pointer. Here's an example:

classA { Public:voidFun () {cout<<"A::fun"<<Endl; }};
classD | PublicA { Public:voidFun () {cout<<"B::fun"<<Endl; }voidfun0 () {cout<<"B::fun0"<<Endl; }};
intMain () {A*a=NewA; B*b=NewB; A*PA; B*PB;PB=static_cast (a);//The base class pointer displays conversions to the inheriting class pointerPb->fun0 ();p b-Fun ();return 0;}

References:

1. Science Press "C + + program Design"

2. Zeeshan Amjad "ATL on the Hood"

Virtual functions in C + +

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.