Hello, there is a hierarchy of classes, the constructor has input data for each class, everything works for constructors without input data, I’m interested in how to pass arguments from derived classes (if there are several of them) to a single virtual base class.

class E{ public: int i; E(int a){ i=a; } ~E(){ } }; class A:virtual public E{ public: A(int a,int b):E(b){ i=a; } }; class B:virtual public E{ int x; public: B(int a,int b):E(b){ x=a; } }; class C :public B,public A{ int m; public: C(int a,int b,int c,int d,int e):B(b,e),A(c,d){ i=a; } }; 

Help me fix it.

  • I do not understand. In which derived class? You and so in classes A and B transfer in E parameters for the designer. - skegg pm
  • And from what class will the parameters A or B be used? As far as I understand, if a class is inherited as a virtual copy of this class is not created. - username76
  • Do you get some kind of error when compiling? Or what? - skegg
  • Yes, there is an error, and without without input parameters for constructors, class objects are created without any problems and everything compiles perfectly, so the problem is most likely in the transfer of parameters to designers. - username76

3 answers 3

So this is the classic problem of multiple inheritance. In reality, 2 variables appear in class C, both of which belong to the namespace C, only one of them in the base class of class A, the other of class B. The compiler turns out to be in a state of uncertainty: which one to use?

You must manually specify which variable, from which namespace, you want to initialize in the body of the constructor

  C(int a,int b,int c,int d,int e):B(b,e),A(c,d){ A::i=a; } 

or

  C(int a,int b,int c,int d,int e):B(b,e),A(c,d){ B::i=a; } 

That's why I consider multiple inheritance one of the most dangerous parts of C ++.

  • Thanks, this is exactly what I needed. - username76

I have your code causing the following error: "no matching function for call to 'E :: E ()". B. Straustrup writes: "The language guarantees that the constructor of the virtual base class is called (explicitly or implicitly) exactly once - from the constructor of the complete object (that is, from the constructor of the most derived class) ." Your C constructor (int, int, int, int, int) does not invoke the constructor of the virtual base class E (int), the compiler tries to implicitly invoke the default constructor E (), but it cannot because the default constructor is not defined. The constructor for class C can look like this: C(int a,int b,int c,int d,int e): E(a), B(b,e), A(c,d) {}

    Yes, the question is not completely clear, but, as I probably correctly understood, you need a class that stores any data during the program. I advise you to use the simplest in the implementation of the pattern "Loner"

    Loner Pattern