A detailed explanation of virtual function _c language in C + + programming

Source: Internet
Author: User
Tags inheritance types of functions

We know that in the same class you cannot define two functions that have the same name, the number of arguments, and the same type, or else it is "duplicate definition." However, in the inheritance hierarchy of a class, functions that have the same name, the number of parameters, and the same types of functions can appear at different levels.

It was suggested that the same invocation could be used to invoke both the derived class and the same function of the base class. Instead of calling a function of the same name in a different derivation hierarchy in a program, it is called by a pointer instead of a different object name. For example, use the same statement "Pt->display ();" You can call a display function in a different derivation hierarchy by assigning a different value to the pointer variable pt (so that it points to a different class object) before calling.

For example, you have to go to a certain place, if you take the bus, you must determine the destination in advance, and then ride to the destination bus line. If you change to take a taxi, it is much simpler, do not need to check the driving route, because the taxi can go anywhere, as long as the car on the temporary tell the driver where to go. If you want to visit multiple destinations, once you reach a destination and then tell the driver the next destination, it is obvious that "hit" is more convenient than taking a bus. You can take the same taxi no matter where you go. This is an example of achieving different ends in the same form.

Virtual functions in C + + are used to solve this problem. The function of a virtual function is to allow a function with the same name as the base class to be redefined in a derived class, and a function of the same name in a base class and a derived class can be accessed through a base class pointer or reference.

Please analyze this example below. This example starts without using a virtual function, and then discusses the use of virtual functions.

The [example] base class has a function of the same name as the derived class. In the following program student is a base class, graduate is a derived class, and they all have a function with the same name as display.

#include <iostream> #include <string> using namespace std; Declares the base class Student class Student {public:student (int, string,float);//Declare constructor void display ();/Declare output function protected://Protected Member
  , the derived class can access int num;
  String name;
Float score;
};
  The implementation of the Student class member function student::student (int n, string nam,float s)//defines the constructor {num=n;
  Name=nam;
Score=s; } void Student::d isplay ()//define output function {cout<< "num:" <<num<< "\nname:" <<name<< "\nscore:"
<<score<< "\ n";  }//Declare common derived class graduate class Graduate:public Student {public:graduate (int, string, float, float);/declare constructor void display (
)//Declaration output function Private:float pay;
}; Implementation of graduate class member functions void Graduate::d isplay ()//define output function {cout<< "num:" <<num<< "\nname:" <<name
<< "\nscore:" <<score<< "\npay=" <<pay<<endl; Graduate::graduate (int n, string nam,float s,float p): Student (n,nam,s), Pay (p) {}//main function int main () {Student STUD1 (1001, "Li", 87.5);//Define Student class object Stud1 GraduaTe Grad1 (2001, "Wang", 98.5,563.5)//Define graduate class object Grad1 Student *pt=&stud1;//define pointer variable to base class object PT Pt->display ();
  pt=&grad1;
  Pt->display ();
return 0;
 }

The results of the operation are as follows:

num:1001 (stud1 data)
name:li
score:87.5

num:2001 (data in the base class section of Grad1)
Name:wang
score:98.5

If you want to output all the data members of the GRAD1, of course, you can do this by invoking the display function via the object name, such as Grad1.display (), or by defining a pointer variable ptr that points to the graduate class object, and then pointing the PTR to Gradl, Called again with Ptr->display (). This is certainly possible, but if the base class has more than one derived class, each derived class produces a new derived class, creating a class family of the same base class. Each derived class has a function display with the same name, and in the program to invoke a function of the same class that is not the same as the same family, you define multiple pointer variables that point to each derived class. Both approaches are inconvenient, requiring different invocation methods when calling a function of the same name of a different derived class, as in the previous case, to the different destinations to take the specified different bus, one by one, and can not be mistaken. It would be nice if you could invoke all the same functions of the same class in the same way.

The problem can be solved smoothly with virtual function. Here are some changes to the program, in the student class to declare the display function, in the leftmost add a keyword virtual, that is

  virtual void display ();


This declares the display function of the student class as a virtual function. No other parts of the program are changed. Re-compile and run the program, please note the analysis Run results:

num:1001 (stud1 data)
name:li
score:87.5

num:2001 (data in the base class section of Grad1)
Name:wang
score:98.5
pay=1200 (this item was not previously)

See! This is the Magic function of virtual functions. Now using the same pointer variable (pointer variable to the base class object) not only outputs all the data for the student STUD1, but also outputs all the data for the graduate Grad1, indicating that the GRAD1 display function has been called. With the same invocation form "Pt->display ()", and PT is the same base class pointer, can call the same family of different kinds of virtual functions. This is polymorphism, and different objects have different responses to the same message.

Description: The base class pointer is used to point to the base class object, if it points to a derived class object, a pointer type conversion is made, and the pointer to the derived class object is first converted to a pointer to the base class, so the base class pointer points to the base class part of the derived class object. A member function in a derived class object cannot be invoked through a base class pointer until the program is modified. Virtual functions break through this limitation, and in the base class section of a derived class, the virtual function of the derived class replaces the original virtual function of the base class, so when you call the base class pointer to a derived class object, the virtual function of the derived class is invoked when the virtual function is invoked. It is important to note that only virtual functions declared with virtual have the above effect. If you do not declare a virtual function, it is not possible to attempt to call the derived class's non-virtual function through the base class pointer.

The function of virtual function is very practical. In object-oriented programming, class inheritance is often used to preserve the attributes of the base class to reduce the time for new class development. However, some member functions inherited from the base class are not fully adapted to the needs of the derived class, for example, the display function of the base class outputs only the data of the base class, and the display function of the derived class needs to output the data of the derived class. We used to make the output function of a derived class different from the output function of the base class (such as display and display1), but it would be inconvenient to have many different function names if the derivation is more hierarchical. If you take a function of the same name, an overlay with the same name occurs.

The use of virtual functions is a good solution to this problem. You can see that when you declare a member function of a base class as a virtual function, you are allowed to redefine the function in its derived class, give it new functionality, and you can call a function of the same name by pointing to a pointer to a base class that is not homogeneous in the same class. The dynamic polymorphism realized by virtual function is that different objects in the same family are not identical in the same class, and respond to the same function call differently.

Virtual functions are used in the following ways:
Declare member functions as virtual functions in the base class with virtual.
This allows you to redefine the function in a derived class, give it new functionality, and easily be invoked. When you define a virtual function outside of a class, you do not need to add virtual.
Redefining this function in a derived class requires that the function name, function type, number of function arguments, and type are all the same as the virtual functions of the base class, and the body of the function is redefined based on the needs of the derived class.
C + + stipulates that when a member function is declared as a virtual function, the function of the same name in its derived class automatically becomes a virtual function. Therefore, when a derived class declares the virtual function, it can be either virtual or not, but it is customary to add virtual to the function at each level, making the program clearer. If a virtual function of a base class is not redefined in a derived class, the derived class simply inherits the virtual function of its direct base class.
Defines a pointer variable that points to a base class object and makes it point to the object in the same family that needs to call the function.
This virtual function is called through this pointer variable, which is called a function with the same name as the object to which the pointer variable points.
Using the combination of virtual function and pointer variable pointing to the base class object, we can conveniently call the same class of similar functions with the same name, as long as the base class pointer is used. A function of the same name in these objects can be continuously invoked if the pointer constantly points to an object that is not homogeneous in the same class. It's like saying, keep telling the taxi driver where to go, and then the driver will send you to where you want to go.

It is necessary to note that a non-virtual function that is sometimes defined in a base class is redefined in a derived class (such as the area function in an example). If the member function is called with a base class pointer, the system calls the member function of the base class part of the object, and if the member function is called with a derived class pointer, the system calls the member function in the derived class object. This is not a polymorphic behavior (using different types of pointers) and does not use the function of a virtual function.

The function overload described previously deals with a function with the same name on the same level, whereas a virtual function deals with a function problem with the same name on different derived hierarchies, which is horizontal overload, which can be interpreted as a vertical overload. Unlike overloading, however, the header of a virtual function of the same class family is the same, and when the function is overloaded, the header of the function is different (the number or type of arguments is different).

Under what circumstances should a virtual function be declared
When using virtual functions, there are two points to note:
You can declare a member function of a class only with virtual, making it a virtual function, not declaring a normal function outside of a class as a virtual function. Because the purpose of a virtual function is to allow the virtual function of a base class to be redefined in a derived class. Obviously, it can only be used in the inheritance hierarchy of a class.
After a member function is declared as a virtual function, a class in the same class can no longer define a function with the same name that is not virtual but has the same parameters (including number and type) and function return value type as the virtual function.

Based on what considerations do you declare a member function as a virtual function? Mainly consider the following points:
First look at whether the class that contains the member function will act as a base class. Then see if the member function can be changed after inheriting the class, and if you want to change its functionality, you should generally declare it as a virtual function.
If a member function does not need to be modified after the class is inherited, or if the derived class does not use the function, do not declare it as a virtual function. Don't just consider declaring all member functions in a class as virtual functions as a base class.
You should consider whether calls to member functions are accessed through object names or by base class pointers or references, and if they are accessed through base class pointers or references, you should declare them as virtual functions.
Sometimes, when a virtual function is defined, its function body is not defined, that is, the function body is empty. Its function simply defines a virtual function name, and the specific function is left to the derived class to add.

Need to explain: the use of virtual functions, the system must have a certain amount of space overhead. When a class has a virtual function, the compilation system constructs a virtual function table for the class (Virtual functions table, abbreviated vtable), which is an array of pointers that holds the entry address of each virtual function. The time overhead of the system in dynamic association is very low, therefore, polymorphism is efficient.

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.