A static binder is a binder that is made during the program compilation connection phase. Also known as the early risers, because this kind of work is done before the program runs. The polymorphism it supports is called compile-time polymorphism. For example: overloaded functions, overriding functions in subclasses. The advantage of static linking is that it is fast and inexpensive, but requires the programmer to predict what objects to use.
A dynamic binder is a binder that is performed while the program is running. Also known as late-stage linking. Virtual functions are required to implement. The disadvantage is that the call is slow, but itself flexible.
The default constructor, which functions as a copy of all data members of a well-known object (including many, of course, the address of a virtual function table) to all data members of the corresponding object.
#include <iostream>
Const double P = 1.0;
using namespace Std;
class people
{
Public
People () {};
Double age () Const{return 0.0;}
};
Class Student
{
Public
Student (int i) {R = i;}
Double age () Const{return p*r*r;} Covered
Protected
int R;
}
void func (people& s)
{
Cout<<s.age () <<endl;
}
int main ()
{
Peopel people;
Student Student;
Func (people); Result is 0.0
Func (student); Result is 0.0
return 0;
}
Why there is no implementation polymorphism, because the static binder, at compile time to determine the function of the call. Assign the student to the people will be assigned to the value, see the above third, did not student the address of the age () function to people, (because the subclass all inherit the information of the parent class, but also extended, to the parent class, only the inherited information is left all, The expanded information is all lost) so all are called the People's age () method. So the disadvantage of static linking is that it requires the programmer to specify which object to call the method, without flexibility.
If you precede the age () method with the keyword virtual, which indicates that this is a virtual function, you can implement dynamic linking. What's the reason? Because of the virtual function, there is a virtual function table, which is an address in the class. Addresses are virtual functions, and placed in order, the virtual function address of the parent class is in front. So after the assignment, the address of the virtual function does not change, but the subclass overrides the virtual function in the parent class, so the function in the virtual function table is called, regardless of the object being called.
Do not understand the students, please Baidu virtual function table, the above are described in detail and diagram.
This article from "Very blog" blog, reproduced please contact the author!
The realization and principle of 02 polymorphism in C + + advanced route