virtual function and dynamic Binder in C + +

Source: Internet
Author: User
Tags constructor requires

The basic idea of object-oriented programming is to simulate the world with program, which makes its fundamental characteristics very humanized, such as encapsulation, inheritance, polymorphism, and so on, and virtual function is the chief of polymorphism in C + +. To achieve polymorphism, the C + + compiler also revolutionized the feature of a dynamic binder (or late binding).

Virtual function is also the key to MFC programming, MFC programming There are two main methods: one is to respond to various messages, for the corresponding message processing. The second is to overload and overwrite the virtual function to implement some of its own requirements or to change some of the system's default processing.

The position of virtual function is so important, it is Hugan to know it and know its reason is good for our programming ability improvement. Below and listen to my word.

Analysis of the realization process of polymorphism and dynamic joint-edit

First, the basis of a little (limited to space, please refer to the corresponding C + + books):

1. Polymorphism: Using pointers to the underlying class to dynamically invoke the attributes of a function in its derived class.

2, dynamic Link: In the running phase, the function of the call to the corresponding function of the way to connect, also known as the run-time link or late bundle.

Second, process description:

1. The compiler discovers that there is a virtual function in a class, and the compiler will immediately generate a virtual function table vtable for this class (followed by the analysis of the vtable). The table entries for the virtual function table are pointers to the corresponding virtual functions.

2, the compiler implicitly inserts a pointer vptr in this class (for the VC compiler, it is inserted in the first position of the class).

There is a way for you to perceive the existence of this implied pointer, although you cannot see it directly in the class, but you can compare the size of the class containing the virtual function with the size of the class without the virtual function, and you can see that the pointer does exist.

3. When invoking the constructor of this class, in the constructor of the class, the compiler implicitly executes the associated code of Vptr and vtable and points the vptr to the corresponding vtable. This links the class to the vtable of this class.

4. When invoking the constructor of the class, the pointer to the underlying class has now become the this pointer to the specific class, so that the correct vtable can be obtained by relying on the this pointer to achieve polymorphism. This is the time to actually connect to the function body, which is the dynamic link.

Third, vtable analysis:

Analysis 1: The virtual function table contains the addresses of all the virtual functions of this class and its parent class. If it does not overload a virtual function of the parent class, the corresponding table entry in vtable points to this function of its parent class. Instead, point to this function after the overload.

Analysis 2: Virtual functions are still virtual functions after they are inherited, and virtual functions are very strictly sorted in the order in which they appear, so the vtable of a defined virtual function corresponds to a fixed position in the vtable n,n is a constant that is determined at compile time. So, using Vptr plus the corresponding n, you can get the entry address of the corresponding function.

The compiler invokes the assembler code of the virtual function (refer to in C + +):

Push Funparam; First, the function parameters are pressed stack

Push Si; The this pointer presses the stack to ensure that the current class is operating on

mov Bx,word ptr[si]; because VC + + compiler will vptr placed in the class's first position, so BX inside for vptr

Call word ptr[bx+n]; calls a virtual function. n = The position of the called virtual function in the corresponding vtable

Pure virtual function:

First, the introduction of the reasons:

1. In order to facilitate the use of polymorphic features, we often need to define virtual functions in the base class.

2, in many cases, it is unreasonable for the base class itself to generate objects. For example, animals as a base class can derive from Tigers, peacocks, and other subclasses, but animals themselves produce objects that are clearly irrational.

In order to solve the above problem, the concept of pure virtual function is introduced, and the function is defined as pure virtual function (method: Virtual ReturnType function () = 0;), the compiler requires that it must be overloaded in a derived class to achieve polymorphism. Classes that also contain pure virtual functions are called abstract classes and cannot generate objects. This is a good solution to these two problems.

Ii. the essence of pure virtual function:

1, the class contains pure virtual function then its vtable table is not complete, there is an empty, so, can not generate objects (the compiler is absolutely not allowed to invoke a nonexistent function is possible). In its derived class, unless this function is overloaded, the vtable table of this derived class is incomplete and cannot generate objects, that is, it also becomes a pure virtual base class.

Virtual functions and constructs, destructors:

1. The constructor itself cannot be a virtual function, and the virtual mechanism does not work in the constructor (the dummy function in the constructor will only call its local version).

Consider that using a virtual mechanism in a base class constructor might call a subclass, where the subclass has not yet been generated, and what the consequences are!?。

2. The destructor itself often requires a virtual function, but the virtual mechanism does not work in the destructor.

If a virtual function is used in a class, the destructor must be a virtual function, such as using a virtual mechanism to call Delete, and without a virtual destructor, how to guarantee that the delete is the object you want to delete.

Virtual mechanisms also cannot take effect in destructors because they can cause problems with the invocation of virtual functions of classes that have been deleted.

Object slices:

When you map up (a subclass is mapped to a parent class), the vtable of the subclass can be changed completely into the vtable of the parent class. This is the object slice.

Reason: When mapping up, the interface narrows, and the compiler is absolutely not allowed to invoke a nonexistent function, so the entry of the newly derived virtual function in the subclass will be forcibly "sliced" off in the vtable, and this occurs.

Disadvantages of using Virtual functions

The advantages of a lot of talk about the shortcomings, the main disadvantage of virtual function is low execution efficiency, look at the virtual function caused by the polymorphism of the implementation process, you can understand the reasons.

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.