0

I have seen this question on many other forums but even after following what they said I am still getting errors so I need help. I am trying to inherit the protected and public from mother to daughter while initializing some values for daughter. Here is my code: (Thanks in advance)

#include <iostream>

using namespace std;


class Mother{
private:
    int age;
    string name;
public:
    Mother(string a,string b,int c)
    :name(a),familyname(b),age(c)
    {
        cout<<"The Mother is created\n";
    }
    void returnname(){
        cout<<"My name is "<<name<<" "<<familyname<<"."<<endl;
    }

    void returnage(){
        cout<<"I am "<<age<<" "<<"years old."<<endl;
    }
protected:
    string familyname;
};

class Daughter
:public Mother
{
    private:
    int age;
    string name;
    Daughter(string a,int b)
    :name(a),age(b)
    {
        cout<<"Daughter is created!\n";
    }
};
int main()
{
    Daughter Do("Sarah",10);
    Do.returnname();
    Do.returnage();
}

Error message

main.cpp|34|error: no matching function for call to 'Mother::Mother()'|

smac89
  • 39,374
  • 15
  • 132
  • 179
  • 4
    When creating a derived class, the base class must first be created. If you don't tell the derived constructor which base constructor to use, it tries to use the default base constructor. There is no default base constructor, so the compilation fails. Tell the derived constructor to call the corresponding base constructor. `Daughter(string a, int b) : Mother(a, "some family name", b) {}` – JohnFilleau Mar 10 '21 at 01:58
  • 1
    Daughter's constructor is private. – Retired Ninja Mar 10 '21 at 01:59
  • 2
    Compilation issues aside, it seems strange that you can create a daughter without a family name. Also, the way you have this set up, a Daughter *is* a Mother. The classes are better called Base and Derived, not Parent and Child. There's not one Mother object that spawns a Daughter object. – JohnFilleau Mar 10 '21 at 02:00
  • Also seems odd that if Daughter changed her family name it would also change Mother's. – Retired Ninja Mar 10 '21 at 02:01

0 Answers0