Home > database >  How to pass values into the constructor of the base class without the constructor of the child class
How to pass values into the constructor of the base class without the constructor of the child class

Time:12-21

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?

CodePudding user response:

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) {
        }
    };
    

CodePudding user response:

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){
    }
};

CodePudding user response:

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.

CodePudding user response:

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
  • Related