In base_instance_init(), we assigned the base_instance_dump() callback. Thus, we can invoke this function by both global function or instance function of BaseClass class. Additional flags G_TYPE_FLAG_DERIVABLE and G_TYPE_FLAG_DEEP_DERIVABLE are also passed to the GTypeFundamentalInfo struct to enable inheritance.
It’s time to define our Derived type:
C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// derived.h
#ifndef DERIVED_H_
#define DERIVED_H_
#include "base.h"
#include <glib-object.h>
/* Derived object struct */
typedefstruct_Derived{
/* The GTypeClass structure is still the first member of the class structure */
Base parent;
/* should be hidden */
gint derived_instance_i;
}Derived;
/* Derived class struct */
typedefstruct_DerivedClass{
/* The TypeInstance structure is still the first member of the instance structure */
BaseClass parent;
}DerivedClass;
/* non-virtual public method for Derived object */
Our Derived type inherits Base by replacing GTypeClass and GTypeInstance with the corresponding struct of the Base type. According to the memory layout of structs, GTypeClass and GTypeInstance are still the first member of corresponding struct. In derived_get_type(), we register Derived type using g_type_register_static() since it’s not a fundamental at all. And the first parameter is the type id of Base type.
Let’s have some time to look up how to implement polymorphism. In derived_class_init(), we re-assign the base_instance_dump() callback to from the Base‘s implementation to Derived‘s implementation.
Test code:
C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
intmain(){
g_type_init();
my_dump_type(base_get_type());
my_dump_type(derived_get_type());
/*
* Official document:
* Use of g_type_create_instance() is reserved for implementators of
* fundamental types only. E.g. instances of the GObject hierarchy should
* be created via g_object_new() and never directly through
* g_type_create_instance() which doesn't handle things like singleton