Re: Best practise inheritance



On Mon, 2017-03-20 at 16:36 +0100, S. Jacobi wrote:
First of all, inheritance may be the wrong word here in plain c, but
I
don't know how else to name it.

Sorry replied to this from my phone and missed some things...

In different projects I see different approaches how to derive custom
widgets from existing ones. I can roughly group them into 2 to 3.

1) The header only has a typedef to make the struct opaque. All
variables needed are put into the struct in the .c file.

myType.h
typedef struct _MyType        MyType;

myType.c
struct _MyType
{
  GtkWidget   *parent;
  /* additions */
  guint                i;
  ...
};

Note also that this approach imposes that absolutely nothing can derive
from MyType later, because MyType becomes anonymous.


2a) The header defines a private struct, and all variables needed are
put into this private struct.

myType.h
typedef struct _MyTypePriv MyTypePriv;
typedef struct _MyType           MyType;

myType.c
struct _MyTypePriv
{
  GtkWidget   *parent;
  /* additions */
  guint                i;
};

struct _MyType
{
  MyTypePriv  *priv;
};

Actually this approach (2a) I've never seen before, not a good idea,
but possibly works (except for the other detail below)...


2b) Similar to 2a, but the parent is put in the "main" struct, not
the
private part.

myType.h
typedef struct _MyTypePriv MyTypePriv;
typedef struct _MyType           MyType;

myType.c
struct _MyTypePriv
{
  /* additions */
  guint                i;
};

struct _MyType
{
  GtkWidget   *parent
  MyTypePriv  *priv;
};

So in all of these cases, you have missed an important detail:

struct _MyType {
    GtkWidget *parent_instance;

    ... anything else...
}

Is wrong, as it will only reserve one pointer size for the parent
structure, what you have been seeing is always in fact:

struct _MyType {
    GtkWidget parent_instance

    ... anything else ...
}

The parent instance must be known and not anonymous, you need to
include the struct itself as the first member of your derived type, not
merely a pointer to that.

Cheers,
    -Tristan



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]