Functions of virtual functions

Source: Internet
Author: User

The role of a virtual function is to allow you to redefine a function with the same name as the base class in a derived class, and you can access functions with the same name in the base class or the derived class through a base class pointer or reference.

 

For example, a base class and a derived class have functions of the same name.

In the following program, student is the base class, and graduate is the derived class. They all have the function with the same name as display.

# Include <iostream>

# Include <string>

Using namespace STD;

// Declare the base class student

Class student

{Public:

Student (INT, String, float); // declare the constructor

Void display (); // declare the output function

Protected: // protected member. The derived class can access

Int num;

String name;

Float score;

};

// Implementation of student class member functions

Student: Student (int n, string Nam, float s) // defines the constructor.

{Num = N; name = Nam; score = s ;}

Void Student: Display () // defines the output function

{Cout <"Num:" <num <"// nname:" <name <"// nscore: "<score <" // n/N ″;}

 

// Declare the public derived class graduate

Class Graduate: Public student

{Public:

Graduate (INT, String, float, float); // declare the constructor

Void display (); // declare the output function

PRIVATE:

Float pay;

};

// Implementation of the graduate class member function

Void Graduate: Display () // defines the 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); // defines Student Class Object stud1

Graduate grad1 (2001, "Wang", 98.5, 563.5); // defines the graduate class Object grad1

Student * PT = & stud1; // defines the pointer variable pt to the Base Class Object

Pt-> display ();

PT = & grad1;

Pt-> display ();

Return 0;

}

The running result is as follows. Please analyze it carefully.

Num: 1001 (stud1 data)

Name: Li

Score: 87.5

Num: 2001 (basic data in grad1)

Name: Wang

Score: 98.5

 

Next, make some modifications to the program. When declaring the display function in the student class, add a keyword Virtual On the leftmost side, that is

Virtual void display ();

In this way, the display function of the student class is declared as a virtual function. The other parts of the program are not modified. Compile and run the program again. Analyze the running result as follows:

Num: 1001 (stud1 data)

Name: Li

Score: 87.5

 

Num: 2001 (basic data in grad1)

Name: Wang

Score: 98.5

Pay = 1200 (this item was not available before)

 

The dynamic polymorphism implemented by virtual functions is that objects of different classes in the same class family make different responses to the same function call. The usage of virtual functions is as follows:

(1) Use virtual to declare a member function as a virtual function in the base class. In this way, you can redefine this function in the derived class, assign it new functions, and be conveniently called.

When defining a virtual function outside the class, you do not need to add a virtual function.

(2) to redefine this function in a derived class, the function name, function type, number of function parameters, and type must all be the same as the virtual function of the base class, define the function body based on the needs of the derived class.

C ++ stipulates that when a member function is declared as a virtual function, all functions of the same name in the derived class automatically become virtual functions. Therefore, when the derived class re-declares the virtual function, it can be added with virtual or not, but it is used to adding virtual when each layer declares the function to make the program clearer.

If the virtual function of the base class is not redefined in the derived class, the derived class simply inherits the virtual function of its direct base class.

(3) define a pointer variable pointing to the base class object and point it to the object that needs to call the function in the same class family.

(4) use the pointer variable to call this virtual function. In this case, the pointer variable points to an object with the same name.

With the combination of virtual functions and pointer variables of the base class object, you can easily call functions of the same name of different classes in the same class family, as long as you point to the base class pointer first. If the pointer continuously points to objects of different classes in the same class family, it can continuously call functions of the same name in these objects. As mentioned above, the driver keeps telling the taxi driver the destination and then sends you to the destination.

It should be noted; sometimes the non-virtual functions defined in the base class are redefined in the derived class. If the base class pointer is used to call the member function, the system calls the member functions of the basic class in the object. If the pointer of the derived class calls the member function, the system calls the member functions of the derived class object, this is not a polymorphism (using different types of pointers) and does not use the functions of virtual functions.

Previously, the function overload process the same name function at the same level, while the virtual function processes the Same Name function at different derived levels. The former is a horizontal overload, the latter can be understood as vertical overload. However, unlike the overload function, the header of the virtual function of the same class family is the same, while the header of the function during the function overload is different (the number or type of parameters are different ).

 

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.