Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance with base class constructor with parameters [duplicate]

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 of foo.foo(int, int).

What?

like image 671
zeusalmighty Avatar asked Jun 07 '15 16:06

zeusalmighty


People also ask

How can you pass parameters to the constructors of base classes in multiple inheritance?

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.

Can base class constructor be inherited?

Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

What happens to constructor in inheritance?

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.

How constructor are executed in multiple inheritance?

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.


1 Answers

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; } 
like image 92
Dmitry Avatar answered Sep 22 '22 13:09

Dmitry