0

Let us consider ordinary diamond problem but slightly improved. Now class A have constant fields.

struct A {
   const int a;

   A (int _a): a(_a) {}
};

struct B: virtual A {
   const int b;

   B(int _b, int _a): A(_a), b(_b) {}
};

struct C: virtual A {
   const int c;

   C(int _c, int _a): A(_a), c(_c) {}
};

struct D: B, C {
    D(int _a, int _b, int _c): ??? {}
};

So, what would be sensible to write instead of question marks? Or maybe it can be solved different way?

  • 1
    Could you describe (in words) what makes your diamond problem "slightly improved"? I see nothing special in your code. – JaMiT Feb 11 '21 at 00:46
  • @JaMiT So, I want to understand how do I handle the fact that fields are constant. It doesn’t seem that trivial to me. Originally, fields weren’t constant as I remember – math-traveler Feb 11 '21 at 00:48
  • 1
    @math-traveler How is this changing the problem? – Lazar Đorđević Feb 11 '21 at 00:50
  • @math-traveler What difference does `const` make? With or without it, it's a question of how the base object gets constructed, see [c++ diamond inheritance constructor?](https://stackoverflow.com/questions/23360572/c-diamond-inheritance-constructor) for example. – dxiv Feb 11 '21 at 00:51
  • @LazarĐorđević I have no idea how I can create instance of class D. What should I write instead of question marks? – math-traveler Feb 11 '21 at 00:51
  • @math-traveler I suspect you are trying to ask how to use initializer lists, but I would consider that a normal part of the diamond problem. – JaMiT Feb 11 '21 at 00:52
  • @JaMiT well, probably, yes. – math-traveler Feb 11 '21 at 00:53
  • 1
    You are probably looking for: [c++ virtual inheritance](https://stackoverflow.com/questions/2126522/c-virtual-inheritance). Again, ordinary diamond problem. – JaMiT Feb 11 '21 at 00:54

1 Answers1

3

The constructor may be written as follows:

D(int _a, int _b, int _c): A(_a), B(_b, _a), C(_c, _a) {}

Because A is a virtual base class, the D constructor must initialize it despite the fact that it is not a direct base class. When an object of most derived type D is being constructed, D::D will first initialize A, and then run the constructors for B and C. When the B and C constructors run, they will ignore the virtual base class A, since D already initialized it.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • Oh, it really works this way? Sounds really awesome. For some reason I have never heard about this effect of virtuality. Thank you – math-traveler Feb 11 '21 at 00:55