Simple code:
class foo { private int a; private int b; public foo(int x, int y) { a = x; b = y; } } class bar : foo { private int c; public bar(int a, int b) => c = a * b; }
Visual Studio complains about the bar
constructor:
Error CS7036 There is no argument given that corresponds to the required formal parameter
x
offoo.foo(int, int)
.
What?
To pass arguments to a constructor in a base class, use an expanded form of the derived class' constructor declaration, which passes arguments along to one or more base class constructors. Here, base1 through baseN are the names of the base classes inherited by the derived class.
Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
Constructor in Multiple Inheritance in C++ Constructor is a class member function with the same name as the class. The main job of the constructor is to allocate memory for class objects. Constructor is automatically called when the object is created.
For multiple inheritance order of constructor call is, the base class's constructors are called in the order of inheritance and then the derived class's constructor.
The problem is that the base class foo
has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:
public bar(int a, int b) : base(a, b) { c = a * b; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With