user3124361
user3124361

Reputation: 489

constructor of base class is called while declaring a derived class

I have got two files and a base class in each of them. I want to let some functions in derived class use data members inside base class. The problem that I am facing resembles closely to the one given below:

In file BaseFile.h

class Base{
private:
int a, b;
protected:
//some data members and functions that I want to share with derived class
public:
Base(int apple, int ball):apple(a), ball(b) {}
};

In file DerivedFile.h

#include "BaseFile.h"
class Derived : public Base{   //error in this line
//stuffs
};

Whenever I declare the derived class, I get an error saying 'no matching function for call to Base::Base note:: candidate expects 2 arguments 0 provided'. What could be the cause of this problem?

Upvotes: 0

Views: 111

Answers (3)

nkvns
nkvns

Reputation: 600

You are getting this error because Base class doesn't have default constructor (which takes 0 arguments) and from derived class constructor base class default constructor is getting called. This can be fixed in two ways:

  1. Add default constructor to base class
  2. Ensure that Base class constructor is always called as Base(int, int).

Also there is a typo in the Base class constructor code

Base(int apple, int ball):apple(a), ball(b) {}

It should be

Base(int apple, int ball):a(apple), b(ball) {}

Upvotes: 0

Andrei Smeltsov
Andrei Smeltsov

Reputation: 588

First, your initializer list in Base class is wrong. Should be a(apple), b(ball).

Second, you do need to initialize Base class in your Derived class, i.e. call its constructor. Something like

Derived::Derived() :
  Base(0,0) {
}

Upvotes: 3

user4650542
user4650542

Reputation:

You have a constructor in the base class that requires two parameters but no default constructor. My guess is that your derived class does not declare constructors so the compiler is trying to create a default for you. It then has no way of calling the base constructor as the only one it has required 2 params.

Upvotes: 2

Related Questions