Tuesday, December 31, 2019

Solving inheritance ambiguity with composition

Let's say you have the following C++ classes, making use of the observer pattern:

In implementation of class A, you call Notify(T) of CObservable.

When you compile, you will get a message that there is ambiguity in calling Notify(), because the compiler does not know if it should call Notify(T) with class T1 as a parameter or T2.

The solution is to remove CObservable from inherited classes and introduce a field, i.e. using composition over inheritance. You also need to have a registerT2Observer() method that in turn calls the register method of CObservable:

No comments: