Summary of the implementation principles of polymorphism by the c ++ Compiler (1)
Question: Define an empty type without any member variables or member functions. What is the result of sizeof operation on this type?
The result is 1. Because an empty instance does not contain any information, the result is 0 after sizeof calculation, but when declaring an instance of any type, the memory must occupy a certain amount of space. Otherwise, these instances cannot be used. The Compiler determines the memory size.
Continue: if you add a constructor and destructor to this type, what is the result?
Or 1, because we only need to know the address of the function to call constructor and destructor, and the address of these functions is only related to the type and has nothing to do with the type instance, the compiler does not add any additional information to the two functions in the instance.
Continue: What if I change the destructor to a virtual function? What is the result?
The c ++ compiler will generate a virtual function table for this type if it finds a virtual function in the type, add a pointer to the virtual function table to each instance of this type. on 32-bit machines, the pointer type is 4 bytes and the result is 4 to 64-bit machines, the pointer size is 8 bytes and the result is 8.
Implementation of object-oriented Polymorphism
Polymorphism: The same invocation statement has many different manifestations.
See the following example:
- class animal
- {
- public:
- void sleep()
- {
- cout<<"animal sleep"<<endl;
- }
-
- void breathe()
- {
- cout<<"animal breathe"<<endl;
- }
- };
-
- class fish:public animal
- {
- public:
- void breathe()
- {
- cout<<"fish bubble"<<endl;
- }
- };
-
- int main(void)
- {
- fish fh;
- animal *pAn=&fh;
- pAn->breathe();
- return 0;
- }
The parent class Pointer Points to the subclass object and calls the breathe method. The result is animal breathe, that is, the breathe method of the parent class is called. This does not achieve polymorphism. The C ++ compiler determines the address of the function called by each object during compilation, which is called the early binding ), when the fh address of the fish object is assigned to the pAn pointer of the parent class, the C ++ compiler performs type conversion, it holds that the pAn pointer variable of the parent class stores the address of the animal object. When pAn-> breathe is executed in the main function, the breathe function of the animal object is called.