It seems that some people do not quite understand this yet. I tried to use the C code to describe some implementation methods related to the C ++ class.
Classes ABC and BC inherit from a and all have virtual functions F (). The Destructor are virtual functions.
C ++ code
// ---------
Struct {
A (){
}
Void F (){
Printf ("Class A \ n ";
}
Virtual ~ A (){
}
};
Struct B: Public {
B (){
}
Virtual void F (){
Printf ("Class B \ n ";
}
Virtual ~ B (){
}
};
Struct C: Public {
C (){
}
Void F (){
Printf ("Class B \ n ";
}
Virtual ~ C (){
}
};
Main (){
A * P = new;
P-> F ();
Delte P;
P = new B;
P-> F ();
Delete P;
}
// C language description. Ignore the syntax. Otherwise, you need to write a lot of typedef definition types.
Assume that c_a () is the destructor of the constructor d_a () as a, and vt_a is the virtual function table structure of.
B and C are similar
First construct the structure
Struct vt_a {
Destructfun_ptr;
Virtual_f_ptr;
};
Here, the vtable and a structures of B and C are the same, and there is no extended function.
Vt_ B {
Vt_a father ;//
// Other extended functions are listed below
};
Struct {
Vt_a vtable;
// Other member variables of
...
};
Struct B {
A father_a;
// Other member variables of B
};
C and B are similar
// Generate a virtual function table
Vt_a vtable_a = {
D_a, vf_a_f;
};
Vt_ B vtable_ B = {
D_ B, vf_ B _f;
};
Vt_c vtable_c = {
D_c, vf_c_f;
};
Compile
P = new;
P-> F ();
Delete P;
Compile
// First sentence
P = new_op (sizeof (a); // corresponding new function (global, local), can be considered as malloc
A * pA = (A *) P;
Pa-> vtable = vtable_a; // for different subclasses, vtable points to different tables.
Pa-> c_a (PA );
// Second sentence
Pa-> vtable-> virtual_f_ptr (PA); // here is the implementation method of polymorphism (different vtable implementation calls the virtual function of subclass)
// Sentence 3rd
Pa-> vtable-> destructfun_ptr (PA );
Delete_op (PA); // corresponding delete function, which can be considered as free
/// Finally, the implementation method of the Chain Structure
D_a (){
// Custom code
...
}
D_ B ()
{
// Custom code
...
// Add the Compiler
D_a (this );
}
This is the chain structure principle.
During compilation, the parent class of a class must be certain. You can think that after the destructor of a subclass is called, this degrades to the type of the parent class, at this time, the destructor of the parent class (implemented by the compiler) will be called until there is no parent class.
Multi-inheritance is similar to single-inheritance, but the memory layout is different. During subclass and parent class pointer conversion, there may be offset values.