Method for C-simulated C object model
1. Proposed outline:
2. Status
The current method of C used in our company is to join some "function type members variables" in an object, which everyone is very clear. However, this simulation method has some shortcomings:
1. Take a large space: Multiple objects of the same category will protect the same function pointer. Such as a desktop, if there is 10 Button, these Button all member functions, will occupy 200 bytes of space And actually only 20 bytes. ---- Pbutton has 5 member functions.
2. Copy all of these function pointer to the object each time you create an object. Add the time created by the object.
3. Increase member functions, the layout of this type of object and its derivative type will change, and the offset address of the member will change. ----- If the new member function is placed in the end, only its class is The layout will change.
4. Other functions such as dynamic type identification to increase objects is difficult, almost impossible.
5. This method is blurred the concept of 'object' and 'class'. The member function is the same for each instance of the consent object. However, the current simulation method allows the client to modify a 'object' member function. . Not a member of 'class''. The concept is blurred, and people will easily turn some errors.
6. When implementing the virtual function, the customer needs to know the same name function of the base class. Although the normative naming method can avoid remembering these function names, but so that the "base class method" is still not very convenient.
4. Creative content:
All objects of the same class, only a copy of the function pointer. Object and class layout, such as (Figure 1);
All objects of the system are generally divided into two; ordinary objects and class objects, a normal object is an instance of a class object; class objects must be purchased with ordinary objects. The best implementation is to declare class objects as global All members of the class object must be initialized. Each type of object is only one. And is a constant.
Therefore, you can declare the class object as a global constant variable.
Top Base Class
Class_ptr
Data MEMBERS
......
Class Base1
Class_ptr
Data MEMBERS
......
Objcet
Class
Top Base Class
BASE_CLASS_PTR
Function MEMBERS
(* fun1) ()
(* fun2) ()
(* fun3) ()
Other Class Info
Class_name
OBJ_SIZE
......
Class Base1
BASE_CLASS_PTR
Function MEMBERS
(* fun1) ()
(* fun2) ()
(* fun3) ()
Other Class Info
Class_name
OBJ_SIZE
......
......
NULL
Fun1
Fun2
Fun2
Class Base1
Class_ptr
Data MEMBERS
......
Class Base1
BASE_CLASS_PTR
Function MEMBERS
(* fun1) ()
(* fun2) ()
(* fun3) ()
Other Class Info
Class_name
OBJ_SIZE
......
Fun1
Fun2
Fun2
Fun1
Fun2
Fun2
(figure 1)