The essence of polymorphism and the basic use of virtual functions

Examples are as follows:

#include <iostream>
using namespace std;

class Father {
    
    
public:
	void play() {
    
    
		cout << "到KTV唱歌..." << endl;
	}
};

class Son :public Father {
    
    
public:
	void play() {
    
    
		cout << "一起打王者吧!" << endl;
	}
};

void party(Father **men, int n) {
    
    
	for (int i = 0; i<n; i++) {
    
    
		men[i]->play();
	}
}
int main(void) {
    
    
	Father father;
	Son son1, son2;
	Father* men[] = {
    
     &father, &son1, &son2 };

	party(men, sizeof(men) / sizeof(men[0]));

	system("pause");
	return 0;
}

The output is:
insert image description here

In the above example, the parent class pointer contains the subclass pointer. When the subclass pointer calls the method in the subclass, it fails. Instead of calling the method in the subclass, it calls the method with the same name in the parent class!

So, how to solve this problem?
Using a virtual function can solve this problem:

class Father {
    
    
public:
	virtual void play() {
    
    
		cout << "到KTV唱歌..." << endl;
	}
};

The output is:
insert image description here

This is polymorphism! It can be known from this that the essence of polymorphism is:
formally, a unified parent class pointer is used for general processing,
but in actual execution, this pointer may point to a subclass object.
Formally, the method of the parent class is originally called, but the method of the same name of the subclass is actually called.

[Note]:
When the program is executed, when the parent class pointer points to the parent class object or the subclass object, it is indistinguishable in form!
Only through the polymorphic mechanism can the corresponding method be executed.

The basic use of virtual functions:
the definition of virtual functions:
use virtual before the return type of the function,
only add virtual to the declaration of the member function, do not add virtual to the implementation of the member function

Inheritance of virtual functions:
 If a member function is declared as a virtual function, then its subclass [derived class], and the subclass of the subclass, the inherited member function is also automatically a virtual function.
If you rewrite this virtual function in the subclass, you don't need to write virtual, but it is still recommended to write virtual, which is more readable!

Guess you like

Origin blog.csdn.net/weixin_46060711/article/details/124458506