Reputation: 31
In C++, I created a base class called parent. In this class, I create a constructor that can take one parameter. My sub-class name is child. There haven't any constructor in my child class. My code is given below:
#include<iostream>
using namespace std;
class parent{
public:
parent(int number){
cout<<"Value of the number from parent class is: "<<number<<endl;
}
};
class child: public parent{
public:
child(): parent(10){
}
};
int main()
{
child ob(100);
return 0;
}
When I am trying to run the above code, compiler "shows no matching function for call to 'child::child(int)'".
I don't want to create any parameterized constructor in the child class. How can I pass the value of the constructor of the parent class? How can I solve this problem?
Upvotes: 3
Views: 857
Reputation: 31
Solution to this type of problem in single inheritance is given in the first comment. But in case of multi level inheritance we can solve by the following way:
#include<iostream>
using namespace std;
class parent{
public:
parent(int number){
cout<<"Value of the number from parent class is: "<<number<<endl;
}
};
class child: public parent{
public:
using parent::parent;//Adding the parent constructor to this scope
child(): parent(10){
}
};
class child2: public child{
public:
using child::child; //Adding the child constructor to this scope
child2(): child(10){
}
};
int main()
{
child2 ob(100);
return 0;
}
//Output: Value of the number from parent class is: 100
Upvotes: 0
Reputation: 409166
You have three alternatives:
Don't use parameters, only use child
default construction
Create a child
constructor taking the arguments that's needed (possibly with a default value)
Pull in the parent
constructor into the child
class:
class child : public parent {
public:
using parent::parent; // Add the parent constructor to this scope
child() : parent(10) {
}
};
Upvotes: 5
Reputation: 105
In your main
Method you try to call a constructor from the child
class with an int
as parameter. This error originates from the absence of this constructor. To pass number
to the parent class you would need a constructor like:
child(int number): parent(number) {}
in your child
class.
Upvotes: 0
Reputation: 1
How can I solve this problem?
Add a using declaration using parent::parent;
in the child class.
class child: public parent{
public:
using parent::parent; //added this using declaration
child(): parent(10){
}
};
Upvotes: 1