## Chaining up

Chaining up is often loosely defined by the following set of conditions:

- Parent class A defines a public virtual method named `foo` and provides a default implementation.

- Child class B re-implements method `foo`.

- In the method B::foo, the child class B calls its parent class method A::foo.

There are various uses to this idiom:

- You need to extend the behaviour of a class without modifying its code. You create a subclass to inherit its implementation, re-implement a public virtual method to modify the behaviour and chain up to ensure that the previous behaviour is not really modified, just extended.

- You need to implement the Chain Of Responsibility pattern: each object of the inheritance tree chains up to its parent (typically, at the beginning or the end of the method) to ensure that they each handler is run in turn.

To explicitly chain up to the implementation of the virtual method in the parent class, you first need a handle to the original parent class structure. This pointer can then be used to access the original class function pointer and invoke it directly. [10]

The function `g_type_class_peek_parent` is used to access the original parent class structure. Its input is a pointer to the class of the derived object and it returns a pointer to the original parent class structure. Instead of using this function directly, though, you should use the `parent_class` pointer created and initialized for us by the G_DEFINE_TYPE_* family of macros, for instance:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    static void
    b_method_to_call (B *obj, int a)
    {
      /* do stuff before chain up */

      /* call the method_to_call() virtual function on the
       * parent of BClass, AClass.
       *
       * remember the explicit cast to AClass*
       */
      A_CLASS (b_parent_class)->method_to_call (obj, a);

      /* do stuff after chain up */
    }

[10] The original adjective used in this sentence is not innocuous. To fully understand its meaning, you need to recall how class structures are initialized: for each object type, the class structure associated to this object is created by first copying the class structure of its parent type (a simple `memcpy`) and then by invoking the class_init callback on the resulting class structure. Since the class_init callback is responsible for overwriting the class structure with the user re-implementations of the class methods, we cannot merely use the modified copy of the parent class structure stored in our derived instance. We want to get a copy of the class structure of an instance of the parent class.