Virtual Functions The following important rules apply to the definition of:
1. If the virtual function appears in the base class and the derived class, only the name is the same, and the formal parameter is different, or the return type is different, then the virtual keyword is not late bound even if it is added.
2. Only member functions of a class can be described as virtual functions, because virtual functions are suitable only for class objects with inherited relationships, so ordinary functions cannot be described as virtual functions.
3. A static member function cannot be a virtual function because a static member function is not restricted to an object.
4. The inline function cannot be a virtual function because the inline function cannot dynamically determine the location in the run. Even though the virtual function defines the definition within the class, the system still considers it to be non-inline at compile time.
5. The constructor cannot be a virtual function, because the object is still an amorphous space when constructed, and the object is an instance of the concrete class only after the construction is complete.
6. Destructors can be virtual functions, and they are usually declared as virtual functions.
In a class with virtual functions, the compiler establishes a virtual function table (virtual table) to record the corresponding virtual function address. Each address corresponds to a virtual pointer, and the size of the pointer is 4 bytes (the compiler generally addresses it in multiples of 4). Virtual tables are stored sequentially. In an instance object of a class, there is a virtual table pointer that points to the virtual table.
Virtual Inheritanceis designed to solve multiple inheritance and avoids duplicate copies. as follows:figure (a), (b), (c) indicates that B inherits from the A,c inherited from the A,d inherits from B and C, so since B and C both inherit from a, so the case of D, there will be two A in class D, duplicate copies, in order to save space, you can define the inheritance of b,c A as virtual inheritance, A becomes the virtual base class, then the inheritance diagram becomes the diagram (e). The code is as follows:
Code
1234 |
class A; class B: public virtual A; //定义成虚继承 class C: public virtual A; //定义成虚继承 class D: public B, public C; //只会出现一个A |
From for notes (Wiz)
List of attachments
Virtual function inheritance and virtual inheritance of C + + learning