The use of virtual functions in C + + detailed explanation __jquery

Source: Internet
Author: User
Tags 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. For example, in the program, in example 12.1 (Specific code view: A typical example of C + + polymorphism), the area function is defined in the Circle class, and an area function is defined in the derived class cylinder of the Circle class. Not only are the two functions the same name, but the number of parameters is the same (all 0), but the function is different, the function body is different. The function of the former is to find the circle area, and the latter is to find the surface area of the cylinder. This is legal because they are not in the same class. The compilation system determines which objects are invoked according to the principle of overriding the same name. The member function area in the derived class cylinder is invoked in Cy1.area () in the example 12.1 program. If you want to call the area function of the direct base class circle in Cy1, it should be represented as cy1. Circle::area (). This method is used to differentiate two functions with the same name. But it's inconvenient.

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 example 12.2. This example starts without using a virtual function, and then discusses the use of virtual functions.

The [Example 12.2] base class has a function with the same name as a 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, 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 \ n "; }//Declare common derived class graduate class Graduate:public Student {public:graduate (int, string, float, float);//Declare constructor void display ();/ /DECLARE 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, "L I ", 87.5)//Define Student Class object STUD1 graduate Grad1 (2001," Wang ", 98.5,563.5)//Define graduate class object Grad1 Student *pt=&stud1;//defines pointer variable pt Pt->display () pointing to the base class object; pt=&grad1; Pt->display (); return 0; The results of the run are as follows:
num:1001 (STUD1 data)
Name:li
score:87.5

NUM:2001 (data in the base class part 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 part 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 base class original

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.