Flexible application of function polymorphism in C ++ & amp; virtual functions

Source: Internet
Author: User

Polymorphism and virtual functions

I. Polymorphism

A derived class object can be used to initialize or assign values to a base class object.

Function polymorphism is actually a flexible application of declarations in different forms of functions. For example, a function with different parameters of the same name represents a type of polymorphism of the function, and a parameter with the same name represents the coverage of the function; if different types of parameters and numbers are used to declare different or identical functions, the program will match the previously declared function model based on the number and type of actual parameters we call, calculate the value.

 

Ii. Virtual Functions

In the inheritance hierarchy of classes, functions with the same name (type and number) can appear in different layers. The member method of the parent class is called in the subclass. You can use the scope of the parent class when calling the subclass object.

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.

An example shows the difference between using a virtual function and not using a virtual function. Both the base class and the derived class have functions of the same name.

Do not use virtual functions:

 

[Cpp]
//
// Student. h
// Programs
//
// Created by bo Yangon 4/17/12.
// Copyright (c) 2012 _ MyCompanyName _. All rights reserved.
//
 
# Ifndef Programs_Student_h
# Define Programs_Student_h
Using namespace std;
 
Class Student
{
Public:
Student (int, string, float );
Void display ();
Protected:
Int num;
String name;
Float score;
};
 
 
# Endif

[Cpp]
//
// Student. cpp
// Programs
//
// Created by bo Yangon 4/17/12.
// Copyright (c) 2012 _ MyCompanyName _. All rights reserved.
//
 
# Include <iostream>
# Include <string>
# Include "Student. h"
Using namespace std;
 
// Define the constructor
Student: Student (int n, string nam, float s)
{
Num = n;
Name = nam;
Score = s;
}
 
Void Student: display ()
{
Cout <"num:" <num <"\ n name:" <name <"\ n score: "<score <" \ n "<endl;
}

[Cpp]
//
// Graduate. h
// Programs
//
// Created by bo Yangon 4/17/12.
// Copyright (c) 2012 _ MyCompanyName _. All rights reserved.
//
 
# Ifndef Programs_Graduate_h
# Define Programs_Graduate_h
# Include "Student. h"
# Include <string. h>
Using namespace std;
 
Class Graduate: public Student
{
Public:
Graduate (int, string, float, float );
Void display ();
Private:
Float pay;
};
 
 
# Endif

[Cpp]
//
// Graduate. cpp
// Programs
//
// Created by bo Yangon 4/17/12.
// Copyright (c) 2012 _ MyCompanyName _. All rights reserved.
//
 
# Include <iostream>
# Include "Graduate. h"
# Include "Student. h"
Using namespace std;
 
Void Graduate: display ()
{
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)
{

}

[Cpp]
//
// Main. cpp
// Student & Graduate
//
// Created by bo Yangon 4/17/12.
// Copyright (c) 2012 _ MyCompanyName _. All rights reserved.
//
 
# Include <iostream>
# Include "Student. h"
# Include "Graduate. h"
Using namespace std;
 
Int main (int argc, const char * argv [])
{
 
Student s1 (1000, "David", 100 );
Graduate g1 (2000, "Jarry );

Student * p = & s1;
P-> display ();

P = & g1;
P-> display ();
Return 0;
}

 


Description: defines a Student class. After the Graduate class inherits the Student class, the two Classes define a display () method together, because the same name is defined in the base class and the derived class respectively, there is no conflict, but there is a problem during the call. In the main function, we define a pointer p pointing to the first address of the parent class object, and then use the pointer p to call the display () function. No problem, we can print the desired data. Then point p to the first address of the Graduate object in the derived class and call the display () method again. You will find that the member objects inherited from the parent class in Graduate are not overwritten, it is still the value of the members in the parent class. It is no problem to print out the members of Graduate. It means that it is impossible to use a pointer to direct different classes to call the same class with the same name in different levels. This requires the use of virtual functions to solve this problem.

Let's make some modifications in the above program: When declaring display () in the Student class, add a keyword virtual

Virtual void display ();

In this way, the Student class display () is declared as a virtual function. In this way, you can achieve the desired effect.

Note: The base class pointer is used to direct the base class object. If it is used to point to a derived class object, the pointer type conversion is performed to convert the pointer of the derived class object to the base class pointer first, therefore, the base class Pointer Points to the base class part of the derived class object.

Before the program is modified, the member functions in the derived class object cannot be called through the base class pointer. The virtual function breaks through this restriction. In the basic class of the derived class, the virtual function of the derived class replaces the original virtual function of the base class. Therefore, after the base class Pointer Points to the object of the derived class, when a virtual function is called, the virtual function of the derived class is called. The preceding functions are available only when virtual functions are declared. If it is not declared as a virtual function, it is not feasible to attempt to call the non-virtual function of the derived class through the base class pointer.

After declaring a member function of the base class as a virtual function, you can redefine the function in its derived class and assign it a new function, in addition, you can call functions with the same name by pointing to objects of different classes in the same class family as the base class pointer. 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.

How to use virtual functions:

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 a derived class and assign it new features for ease of use.

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, and the function body should be redefined according to the needs of the derived class.

3. Define a base class pointer in the main function to refer to the base class object, reference the base class function, point to the derived class object, and reference the derived class function.

C ++ rules: when a member function is declared as a virtual function, all functions with the same name in the derived class automatically become virtual functions. Therefore, functions with the same name in the derived class can be added without adding virtual, and it is easy to understand.

Note: If the virtual functions of the base class are not redefined in the derived class, the derived class simply inherits the virtual functions of its direct base class.

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 objects of different classes.

If the non-virtual function defined in the base class is redefined in the derived class, if the base class pointer is used to call the member function, the system will call the member functions of the base class in the object; if you use a pointer from a derived class to call this member function, the system calls the member function in the object of the derived class. This is not a polymorphism, but a pointer of different types. No virtual function is used.

 

From Anno's column

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.