![]() |
![]() |
![]() |
![]() |
If a base class already implements an interface and a derived class needs to implement the same interface but needs to override certain methods, you must reimplement the interface and set only the interface methods which need overriding.
In this example, MamanDerivedBaz is derived from MamanBaz. Both implement the MamanIbaz interface. MamanDerivedBaz only implements one method of the MamanIbaz interface and uses the base class implementation of the other.
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 33 34 35 |
static void maman_derived_ibaz_do_action (MamanIbaz *ibaz) { MamanDerivedBaz *self = MAMAN_DERIVED_BAZ (ibaz); g_print ("DerivedBaz implementation of Ibaz interface Action\n"); } static void maman_derived_ibaz_interface_init (MamanIbazInterface *iface) { /* Override the implementation of do_action */ iface->do_action = maman_derived_ibaz_do_action; /* * Leave iface->do_something alone, it is already set to the * base class implementation. */ } G_DEFINE_TYPE_WITH_CODE (MamanDerivedBaz, maman_derived_baz, MAMAN_TYPE_BAZ, G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ, maman_derived_ibaz_interface_init)) static void maman_derived_baz_class_init (MamanDerivedBazClass *klass) { /* Nothing here. */ } static void maman_derived_baz_init (MamanDerivedBaz *self) { /* Nothing here. */ } |
To access the base class interface implementation use
g_type_interface_peek_parent
from within an interface's default_init
function.
To call the base class implementation of an interface
method from an derived class where than interface method has been
overridden, stash away the pointer returned from
g_type_interface_peek_parent
in a global variable.
In this example MamanDerivedBaz overrides the
do_action
interface method. In its overridden method
it calls the base class implementation of the same interface method.
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 33 34 35 36 |
static MamanIbazInterface *maman_ibaz_parent_interface = NULL; static void maman_derived_ibaz_do_action (MamanIbaz *ibaz) { MamanDerivedBaz *self = MAMAN_DERIVED_BAZ (ibaz); g_print ("DerivedBaz implementation of Ibaz interface Action\n"); /* Now call the base implementation */ maman_ibaz_parent_interface->do_action (ibaz); } static void maman_derived_ibaz_interface_init (MamanIbazInterface *iface) { maman_ibaz_parent_interface = g_type_interface_peek_parent (iface); iface->do_action = maman_derived_ibaz_do_action; } G_DEFINE_TYPE_WITH_CODE (MamanDerivedBaz, maman_derived_baz, MAMAN_TYPE_BAZ, G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ, maman_derived_ibaz_interface_init)) static void maman_derived_baz_class_init (MamanDerivedBazClass *klass) { /* Nothing here. */ } static void maman_derived_baz_init (MamanDerivedBaz *self) { /* Nothing here. */ } |