Re: GObject constructors



2005/11/9, Jacob Kroon <jacob kroon gmail com>:
> I'm having problems with figuring out how to initialize my data properly.
> My scenario is that I have:
>
> struct Parent {
>     GObject parent;
>     float *data;
> }
>
> struct ParentClass {
>     GObjectClass parent;
>     int data_size;
> }
>
> struct Child {
>     Parent parent;
> }
>
> struct ChildClass {
>     ParentClass parent;
> }
>
> Each subclass of Parent will use different, but fixed data sizes, so I
> want Child to tell Parent how much
> data it needs, and then let Parent initialize the data accordingly.
>
> The way I thought would work was this:
>
> 1. In child_class_init(*klass):
>     PARENT_CLASS(klass)->data_size = specific_size_for_this_subclass;
> 2. In parent_instance_init(*obj)
>     klass = PARENT_GET_CLASS(obj);
>     obj->data = g_new(float, klass->data_size);
>
> but this wont work since PARENT_GET_CLASS(obj) in parent_instance_init()
> returns the class for Parent,
> not the subclass ChildClass, so data_size won't have the value I intended.
As I know:

When you create a Class, you'll need to define macros for convertion
from a derived class to the class you want. Then in
parent_instance_init you'll need to Get the data defined in the parent
and define the value on it:

In parent.h definition of the class you'll need unleast the following
definition:

#define PARENT(obj) (G_TYPE_CHECK_INSTANCE_CAST (obj, PARENT, Parent))

Then now you can CAST from a derived class instance to the parent
instance and have access to the parent data (now part of the child
instance), then:

PARENT(obj)->data = g_new(float, klass->data_size);

will set the value of 'data', but MUST be in the
child_intances_init(); at this point when you create a new Parent
derived object (Child in your example), it will init him selft, and
can init the parent data.



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