[OT] Under the Hood of OOP

C

C# Learner

I'm a bit curious about how OOP works "under the hood".

Consider this (C++) class implementation:

<code>

class MyClass
{
int x;

void Method();
};

</code>

Now, as I understand it, this would actually be compiled down to
something like this:

<code>

struct MyClass
{
int x;
};

void MyClass_Method(MyClass *this);

</code>

....where the struct is a kind of C-type struct.

Okay... now to my question -- how does inheritance work at this level?
Does the compiler more or less "copy" the fields from the parent class
(struct) into the child class (struct)? Or does it do something else?

e.g.:

<code>

class Parent
{
public:
int parentField;
};

class Child : public Parent
{
public:
int childField;
};

</code>

Here, Child seems to have parentField and childField. What goes on
"under the hood" to achieve this?
 
S

Stu Smith

To continue your "C-style" example, it would be something like:

struct Parent
{
//
... vtable and type info
//

int parentField;
};

struct Child
{
//
... vtable and type info
//

int Parent_parentField;
int childField;
};

Of course in real life it's more complicated as the 'structs' will likely
have some form of RTTI descriptor pointer, plus a vtable pointer.

Single inheritance is thus relatively easy since you can treat a derived as
a base by ignoring the later members. Multiple inheritance is more
tricky....


HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top