0

Language : C/C++
Problem : Taking the common example, where

  • A is the parent class.
  • B and C both inherited from class A.
  • D is inherited from both B and C

and we want to access A's function through an object of D

Note: it's virtual inheritance! So we know there will be only one object of A.

The question is : Whose object will be first created B's or C's ?

Keeping the hierarchy in mind

   A
 /   \
B     C
 \   /
   D

3 Answers3

0

In short, there is no guarantee in OO itself regarding this.

If you're talking specific implementations or languages (but the question does not) there may be guarantees regarding this.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
  • @AliShahzeb In C++ it depends on the order you're listing the classes you're inheriting, for example, `class D : public B, public C` would construct B before C. – Joachim Isaksson Aug 03 '12 at 12:01
0

Yeah, this problem is sometimes also apostrophed as diamond of death.

Unfortunately, your question cannot be answered: it is based on the current language you are programming in.

For instance, in Scala (where multiple inheritance is allowed for traits), there is a quite rigirous rule for instantiation along the linearization algorithm, there you can find the proper details.

I suppose you're playing with C++. If that's right, take a look on the proper section of the C++ FAQ (the problem is also mentioned there).

rlegendi
  • 10,466
  • 3
  • 38
  • 50
0

If you are talking C++ and the order of instantion of the classes, then it will depend on the inheritance order in the declaration.

So, in

class D :  public B,public C

B will be instantiated first then C.

class D :  public C,public B

C will be instantiated first then B.

Justin Harvey
  • 14,446
  • 2
  • 27
  • 30