Inheritance


Let's consider these two classes -
class myClassBase
{
public:
    int baseMember;
    myClassBase() { baseMember = 0; }
    int baseMethod(int x) { return baseMember + x; }
};
class myClassDerived : public myClassBase
{
public:
    int derivedMember;
    myClassDerived() { derivedMember = 0; }
    int derivedMethod(int x) { return derivedMember + x; }
};

The equivalent C code will be
struct myClassBase
{
    int baseMember;
};
struct myClassDerived
{
    struct myClassBase base;
    int derivedMember;
};
void myClassBase_ctor(struct myClassBase *this)
{
    this->baseMember = 0;
}
int myClassBase_baseMethod(struct myClassBase *this, int x)
{
    return this->baseMember + x;
}
void myClassDerived_ctor(struct myClassDerived *this)
{
    myClassBase_ctor(this);
    this->derivedMember = 0;
}
int myClassDerived_derivedMethod(struct myClassDerived *this, int x)
{
    return this->derivedMember + x;
}

The relation between the classes can be described by a diagram as:
Inheritance
Here are few points to understand this:

up

Want to learn (C/C++ internals) directly from the author using video call? Learn more

Do you collaborate using whiteboard? Please try Lekh Board - An Intelligent Collaborate Whiteboard App