Derive a class from the base class described in the previous page
class myClassDerived : public myClassBase
{
public:
int derivedMember;
int getVal(int x) { return derivedMember + x; }
};
The equivalent C code:
struct myClassDerived
{
struct myClassBase base;
int derivedMember;
};
int myClassDerived_getVal(struct myClassDerived *this, int x)
{
return this->derivedMember + x;
}
struct
{
long abiVerInfo;
char *typeName;
void *baseTypeInfo;
}
myClassDerived_typeInfo =
{
0, // ABI related stuff.
"myClassDerived",
&myClassBase_typeInfo
};
struct
{
void *typeInfo;
int (*fun1)(struct myClassDerived *, int);
}
myClassDerived_vtable =
{
&myClassDerived_typeInfo,
myClassDerived_getVal
};
void myClassDerived_ctor(struct myClassDerived *this)
{
myClassBase_ctor(&this->base);
this->base.vtable = (void*)&myClassDerived_vtable + sizeof(void*);
}
Points to understand
- Like the base class, there is typeinfo and vtable is generated for the derived class.
- The typeinfo contains an extra field, pointer to the typeinfo of base class.
- The constructor of derived class, as expected, calls the base class constructor then does its own initialization.
- The constructor of derived class replaces the vtable of the base with the vtable of derived. This is how the functions of base class are overridden by functions of derived class. We have seen that the function resolution is done by looking at the vtable and the vtable is replaced by the derived class. So all virtual functions will be resolved with the functions which are present in the vtable of the derived class and hence the derived class function will be called.