1

in the following program, I want to derive a class from a base class. In my code everything seems to be OK. However, I am getting error shown in the below program. Please explain the reason for the error, and how to correct it.

#include <iostream>
using namespace std;

struct Base
{
    int x;
    Base(int x_)
    {
        x=x_;
        cout<<"x="<<x<<endl;
    }
};

struct Derived: public Base
{
    int y;
    Derived(int y_)
    {
        y=y_;
        cout<<"y="<<y<<endl;
    }
};

int main() {
    Base B(1);
    Derived D(2);
}

This is the error:

Output:

 error: no matching function for call to 'Base::Base()
 Note: candidate expects 1 argument, 0 provided
Bahubali
  • 141
  • 1
  • 2
  • 8
  • Your base class's constructor takes an argument. Your derived class must therefore construct the base class appropriately. For more information, see your C++ book. – Sam Varshavchik Nov 08 '17 at 01:34

1 Answers1

1

The default constructor (i.e. Base::Base()) will be used to initialize the Base subobject of Derived, but Base doesn't have one.

You could use member initializer list to specify which constructor of Base should be used. e.g.

struct Derived: public Base
{
    int y;
    Derived(int y_) : Base(y_)
    //              ~~~~~~~~~~
    {
        y=y_;
        cout<<"y="<<y<<endl;
    }
};
songyuanyao
  • 169,198
  • 16
  • 310
  • 405