1

I was working with GTK in one of my projects and I noticed that the library supports inheritance. As you can type-cast a child struct to its parent struct and vice versa. Other than GTK I've never seen this used (so flawlessly):

struct parent p = {5};
struct child c;
c = (struct child)p;
c.b = 1;
//c.a = 5, c.b = 1

Does using the parent struct as the first element do this? As this would seem much more neat. But could padding and aligning interfere?

struct parent { int a; }
struct child  { struct parent p; int b; } 

Or does rewriting all parent data make it happen?

struct parent { int a; }
struct child  { int a; int b; }

EDIT I am NOT looking to implement all pillars of OOP in C. My question is only involving type-casting the data in parent and child structs. I have found that GTK uses GObject to do this, but what must be done to achieve what GObject is doing as far as type casting?

Dellowar
  • 3,160
  • 1
  • 18
  • 37
  • 4
    Does that code actually compile? – Kerrek SB Dec 27 '16 at 15:55
  • 3
    Possible duplicate of [Object-orientation in C](http://stackoverflow.com/questions/415452/object-orientation-in-c) (pointed to by http://stackoverflow.com/questions/1237266/how-can-inheritance-be-modelled-using-c) – KevinDTimm Dec 27 '16 at 16:08
  • struct parent { int a; } struct child { struct parent p; int b; } is the right way if you want to go for inheritance in c – Vikash Kesarwani Dec 27 '16 at 16:15
  • Also covered in http://stackoverflow.com/questions/351733/can-you-write-object-oriented-code-in-c#351756 – Schwern Dec 27 '16 at 16:30
  • You need to learn how to implement OOP concepts first, in any other language, and after that to learn how GTK implemented them. Try and learn oop programming first, after that you will be able to learn how to implement oop concepts. – alinsoar Dec 28 '16 at 23:46

0 Answers0