How diamond problem in oops is solved using "shared" strategy?

233 views Asked by At

Diamond problem is handled in some OOPS languages (eg. curl) by having the repeatedly inherited class as "shared"? I want to know how this works. Also, I want to know the role played by primary and secondary constructors in solving the diamond problem in these OOPS languages when shared strategy is used. Suppose there are 4 classes say A,B,C and D. Let the inheritance structure is B and C inherit A and D inherits both B and C. Each class has a variable say A has a, B has b, C has c and D has d. How does the object creation happens for each class?

1

There are 1 answers

1
progmatico On

Citing Wikipedia at https://en.wikipedia.org/wiki/Multiple_inheritance at the Curl bullet:

Curl allows only classes that are explicitly marked as shared to be inherited repeatedly. Shared classes must define a secondary constructor for each regular constructor in the class. The regular constructor is called the first time the state for the shared class is initialized through a subclass constructor, and the secondary constructor will be invoked for all other subclasses.

From here, without knowing Curl and only with the quote above and this, where it is stated that

The object semantics of Curl are similar to those of Java and C++.

Given

    A
   /  \
 B(A) C(A)
   \   /
   D(B,C)

I imagine (I don't know for sure) that the coder is responsible to disambiguate the problem by specifying the qualified name of the constructor to run, when invoking a parent constructor from the D(B,C) subclass.

It looks like A has to be declared shared, and when D is created, B runs a constructor that calls A (primary) constructor, C runs a constructor that calls A (secondary) constructor. The distinction between primary/secondary constructor call is automatic and transparent to the coder.

As two A constructors are invoked, two A objects are created in memory, that is the A class is shared with two different subclasses, but there is not a single "shared" A object, but two independent ones (see also virtual/nonvirtual inheritance that is somehow related (C++).)

For what I've read for several different languages, it is almost always the coder that disambiguates the diamond problem with qualification. Languages just define different or similar schemes of giving an error, or having a criteria to choose one of the multiple ambiguous definitions, like specific search order in the inheritance chain. Some other languages don't even allow multiple inheritance, but in some of these you are allowed to extend functionality by some ohter means (like interfaces).