Alamgir Hossain
Alamgir Hossain

Reputation: 31

How to pass values into the constructor of the base class without the constructor of the child class in c++?

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

Answers (4)

Alamgir Hossain
Alamgir Hossain

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

Some programmer dude
Some programmer dude

Reputation: 409166

You have three alternatives:

  1. Don't use parameters, only use child default construction

  2. Create a child constructor taking the arguments that's needed (possibly with a default value)

  3. 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

Nerrit
Nerrit

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

user12002570
user12002570

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

Related Questions