Let's take a look at the class memory structure:
Class
{
Int;
Public:
OP (INT value) {A = value ;};
Int read () {return ;}
Public
Virtual int as () {return a * ;}
};
For the preceding class description, the memory structure of an instance is as follows (different C ++ implementations are slightly different ):
+ 0000: member variable int
+ 0004: $ A $ vtable Pointer --> + 0000: member function pointer
Why do op and read functions not need to be reflected in the class? Because it is unnecessary.
When C ++ compiles the above class, it will generate a member function similar to the following (different C ++ implementations are slightly different ):
// Op Function
Int $ A $ op @ I _ (A * This, int value) {This-> A = value ;}
// READ function
Int $ A $ read @ _ (A * This) {return this-> ;}
// As Function
Int $ A $ as @ _ (A * This) {return this-> A * This-> ;}
That is to say, the function name itself specifies the class to which the function belongs (even the parameter type). Therefore, the compiler can directly call the member functions of this class when compiling code, the class itself does not need to provide any information.
Example (0 ):
A;
For function calls:
A. Read ();
In this case, a is an instance of a, so the compilation code is:
$ A $ read @ _ (& );
Example (1 ):
A;
For function calls:
A. ();
In this case, a is an instance of a, so the compilation code is:
$ A $ as @ _ (& );
Example (2)
A * pA;
For function calls:
Pa-> Read ();
The generated code is:
$ A $ read @ _ (PA );
Example (3)
A * pA;
For function calls:
Pa-> ();
The generated code is:
(Pa-> $ A $ vtable [0]) (PA );
Note:
If you do not use a pointer to call a function, it is not a virtual function. The call method is the same. For more information, see examples (0) and examples (1)
For pointer calls, example (2) and example (3) are the differences between calling a virtual function and a common member function. Because of this difference, virtual functions must have a place in the class.