I spent a few minutes dissecting the C ++ internal runtime structure
ObjectsWithin metrowerks codewarrior. There's some internal guts that C ++ generates when you make
Objects;
The format is not standardized between compilers, but looking at one
Implementation reveals some of the costs and implications of C ++
ObjectsAnd inheritance.
C ++ breaksObjects
With methods down into data structures and functions, with Function
Pointers used for virtual functions. polymorphism depends on our
Ability to apply fixed unchanging code to diverse data structures and
Get meaningful execution. Therefore we can immediately postulate one
Rule that applies to allObjects, No matter what C ++ feature is used (inheritance, multiple inheritance, virtual base classes, etc): The in-Memory LayoutOf a pointer to Class X must have a fixedLayoutNo matter what real derived type the object has.
I'm only going to describe the case whereObjects
Have virtual functions and run-time type information. Based on
Actual code and compiler settings, the compiler may sometimes eliminate
These features, changing the in-MemoryStructure, but that's a topic for another blog entry.
Codewarrior
(Like always Ally all c ++ compilers, no pun intended) implements virtual
Methods via virtual function tables (vtables), which are static
Structures containing one function pointer for each virtual function.
An object has a pointer to its class's vtable before any other object
Data; there is only one copy of the vtable per class-it's immutable
And shared. (This makesObjectsSmaller than having pointers to each virtual function in the actual object .)
The
Virtual function table actually contains two more entries before
Function pointers: a pointer to a "type ID" structure, a separate
Structure that describes the class itself, andMemoryOffset whose use we'll look at later. So if we have this c ++ code:
Class Foo {
Virtual void a (INT );
Virtual void B (float );
Int C;
Float D;
};
The equivalent C code wowould look something like this:
Struct foo_vtable {
Typeid * type_id_ptr;
Int offset;
Void (* ptr_to_a) (INT );
Void (* ptr_to_ B) (float );
};
Void foo_a (INT ){}
Void foo_ B (float ){}
Static type_id foo_type_id = {...};
Static foo_vtable sfoo_vtable = {& foo_type_id, 0, foo_a, foo_ B };
Struct Foo {
Foo_vtable * vtable; // gets inited to & sfoo_vtable
Int C;
Float D;
};
Class type is stored separately-first PTR in the V-table. motivation for this will be clear later.
Vtable has an offset-also understood later.