Virtual function-related problem analysis, function-Related Problem Analysis

Source: Internet
Author: User

Virtual function-related problem analysis, function-Related Problem Analysis
Zookeeper 1. Static Association and Dynamic Association
The function calls in the source code are interpreted as executing a specific function code block, which is called function name association. In C, this is very simple, because each function name corresponds to a different function. In C ++, this task is more complex due to function overloading. The compiler must check function parameters and function names to determine which function to use. However, the C/C ++ compiler can complete such association during compilation. In the compilation process, the Association is called static association and also called early Association. However, virtual functions make this work more difficult. Because the compiler does not know which type of object will be selected. Therefore, the compiler must generate code that can select the correct virtual method when the program is running. This is called dynamic association and also known as late Association.
2. Compatibility Between pointers and reference types
Generally, C ++ does not allow a type of address to be assigned to another type of pointer, or a type of reference to another type:
Double x = 2.5;
Int * pi = & x; // invalid assignment
Long & r1 = x; // invalid assignment
However, as we can see, a reference to a base class or a pointer can reference a derived class object without the need to convert the display type.
Converts a reference to a derived class or pointer to a base class reference or pointer to an upward forced conversion. This removes the need for public inheritance to convert the display type. This rule is part of the is-a relationship. It can be passed during forced upward conversion. That is to say, if A sends B and B to derive C, A pointer or reference can reference object A, object B, or object C.
The opposite process-converting a base class pointer or reference to a derived class pointer or reference-is called downward forced conversion. If the display type conversion is not used, downward forced conversion is not allowed.
3. the compiler uses static join for non-Virtual Methods and dynamic join for virtual methods. The C ++ compiler uses static concatenation by default.
4. Working Principles of virtual functions
Generally, the compiler processes virtual functions by adding a hidden member to each object. The hidden member stores a pointer to the function address array. This array is called a virtual function table. The virtual function table stores the addresses of virtual functions generated for class objects. For example, a base class object contains a pointer pointing to the address table of all virtual functions in the base class. The derived class object contains a pointer to the independent address table. If the derived class provides a new definition of the virtual function, the virtual function table will save the address of the new function. If the derived class does not redefine the virtual function, the virtual function table will save the address of the original version of the function. If the derived class defines a new virtual function, the address of the function will also be added to the virtual function table.
5. Notes
If you re-define a function in a derived class, instead of using the same function feature label to override the base class declaration, you can hide the base class method with the same name, regardless of the parameter feature label. This will introduce two empirical rules:
① If the inherited method is redefined, it should be identical to the original prototype. However, if the returned type is a base class reference or pointer, it can be changed to a reference or pointer pointing to a derived class. This feature is called return type covariant because it allows the return type to change as the class type changes.
② If the base class declaration is overloaded, all base class versions should be redefined in the derived class. If only one version is redefined, the other two versions will be hidden and the derived class objects will not be able to use them.
What are the concepts and features of virtual functions?

Definition
A virtual function must be a non-static member function of the base class. Its access permission can be protected or public. The general form of defining a virtual function in the class definition of the base class is as follows: virtual function return value type virtual function name (parameter table) {function body}
Edit the role of this section
The role of a virtual function is to implement dynamic association, that is, to dynamically select an appropriate member function in the running stage of the program. After defining a virtual function, you can redefine the virtual function in the derived class of the base class. The newly defined function in the derived class should have the same number and type as the virtual function. To implement unified interfaces and different definition processes. If the virtual function is not redefined in the derived class, it inherits the virtual function of its base class. When the program finds the keyword virtual before the virtual function name, it automatically uses it as a dynamic concatenation processing, that is, it dynamically selects the appropriate member function when the program is running. ([2010.10.28] Note: the downlink semantics may cause misunderstanding. The actual effect should be: If yes: base-> Derive1-> Derive2 and their virtual functions func () use the Base class and its own type Derive1 when accessing the instance of the derived class Derive1, you can also access the func () implemented by derive1 ().) Dynamic Association stipulates that virtual functions can only be called by referring to the pointer of the base class or the reference of the base class object. The format is as follows: refers to the pointer variable name of the base class-> the reference name of the virtual function name (real parameter table) or base class object. the virtual function name (real parameter table) is a type of C ++ polymorphism. For example, a subclass inherits a function (method) of the parent class ), if we direct the pointer of the parent class to a subclass, we must set the function (method) of the parent class to virtual (virtual function ). By using virtual functions, we can flexibly bind resources dynamically, at a certain cost. If the function (method) of the parent class is not necessary or cannot be implemented at all, you can set this function (method) to depend entirely on the subclass for implementation) set to virtual function name = 0. We call such a function (method) a pure virtual function. If a class contains pure virtual functions, this class is called an abstract class.
Edit this example
Virtual function instance
# Include <iostream. h> class Cshape {public: void SetColor (int color) {m_nColor = color;} void virtual Display (void) {cout <"Cshape" <endl;} private: int m_nColor ;}; class Crectangle: public Cshape {public: void virtual Display (void) {cout <"Crectangle" <endl ;}; class Ctriangle: public Cshape {void virtual Display (void) {cout <"Ctriangle" <endl ;}; class Cellipse: public Cshape {public: void virtual Display (void) {cout <"Cellipse" <endl ;}}; void main () {Cshape obShape; Cellipse obEllipse ;...... remaining full text>

What is the role of virtual functions in C ++? How should it be used?

The virtual function is associated with polymorphism, And the polymorphism is associated with inheritance. Therefore, this article is all about the inheritance level. Without inheritance, there is nothing to talk about.

The following is an understanding of the virtual functions of C ++.

1. What is a virtual function (if you don't know what is a virtual function, but want to know it urgently, you should start from here)

Simply put, member functions modified by virtual keywords are virtual functions. The role of virtual functions is explained in professional terms by implementing Polymorphism. Polymorphism separates interfaces from implementations. interpreting with image languages means implementing a common approach, however, different strategies are adopted due to individual differences. Let's take a look at a simple piece of code.

Class {

Public:

Void print () {cout <"This is A" <endl ;}

};

Class B: public {

Public:

Void print () {cout <"This is B" <endl ;}

};

Int main () {// for future convenience, the main () code is called main1

A;

B B;

A. print ();

B. print ();

}

Through the print () interface of class A and class B, we can see that these two classes adopt different policies due to individual differences, and the output results are also expected, this is A and This is B, respectively. But does this actually enable polymorphism? No. Another key to polymorphism is that all objects are operated by pointers or references to the base class. Now let's change the code in main.

Int main () {// main2

A;

B B;

A * p1 = &;

A * p2 = & B;

P1-> print ();

P2-> print ();

}

Run the command to check the result. The problem is that p2 points to the class B object but calls the print () function of class A, which is not the expected result, to solve this problem, you need to use virtual functions.

Class {

Public:

Virtual void print () {cout <"This is A" <endl ;}// it is now A virtual function.

};

Class B: public {

Public:

Void print () {cout <"This is B" <endl;} // do I need to add the keyword virtual in front of it?

};

Without A doubt, the print () member function of class A has become A virtual function, so does the print () of class B become A virtual function? The answer is Yes. We only need to set the member functions of the base class to virtual, and the corresponding functions of the derived class will automatically become virtual functions. Therefore, print () of class B is also a virtual function. If you need to use the virtual keyword to modify the corresponding function of the derived class, it is your own problem.

Run the main2 code again. The output result is This is A and This is B.

Now let's take a look at it. I will make a simple conclusion that the pointer to the base class will call its corresponding functions based on different class objects when operating on its polymorphism class objects, this function is a virtual function.

2. How can virtual functions be implemented? (If you haven't read The book "Inside The C ++ Object Model" but are eager to know it, you should start from here)

How does a virtual function call its corresponding functions based on different objects? Now let's analyze the virtual functions... the remaining full text>

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.