When we talk about polymorphism, let's look at what is hard coded and soft code: Hard coding is to write code dead, resulting in a lack of elasticity, reduced scalability, such as in the code if......else ... ; Switch......case.
This code is usually hard coded, and the code in the project is much more, which is equivalent to explaining the code's flexibility, scalability, flexibility, and so on.
Therefore, we should try to use soft coding, popular point is "Don't say dead, leave a little leeway to turn." Polymorphism is the reflection of this soft coding feature, so let's take a look at polymorphism here.
Polymorphism is an abstraction that abstracts the characteristics of things, and then we don't care about the concrete form of things.
For example, for a worker this kind of thing, his characteristic is the work, as for what worker, he does what work, we do not care about, as long as we are "the worker." Work "this way to call. Then he's going to work for us.
So why don't we abstract out other features and just abstract the job feature? Because we are only interested in this feature, what he has to eat, sleep, toilet and other characteristics we do not care about. With polymorphism, we can implement the soft code!
After explaining the concept of polymorphism, let's look at the implementation of polymorphism (C + +):
The implementation of polymorphism is through a virtual function table (VTable), and each class, if it has a virtual function, has a virtual function table, All objects share this one vtable. This concept is also known as the dynamic Binder, and the static binder, which is determined by the nature of the program's execution, and we'll look at where it's "moving" and "static".
First look at a piece of code:
class C0
...{
public:
void Test()
...{
cout << "call C0 Test()。" << endl;
}
};
This class has no virtual functions, and calls are static calls. The code to invoke is as follows:
// 静态编译(早绑定 early binding)
C0 *pO0;
C0 obj0;
pO0 = &obj0;
pO0->Test();
它的反汇编代码如下:
// 直接调用函数(已经知道地址)
00401432 mov ecx,dWord ptr [ebp-0Ch]
00401435 call @ILT+160(C0::Test) (004010a5)
Here's a look at the class with the virtual function:
class C1
...{
public:
virtual void Test()
...{
cout << "call C1 Test()" << endl;
}
};
class C11 : public C1
...{
public:
void Test()
...{
cout << "call C11 Test()" << endl;
}
};