Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does my code work without inheritance but not with inheritance in C++?

No matter what I try, the code works without inheritance but never with.

I tried different ways of implementing the constructor but none actually helped.

The error that I keep getting is: no matching function for call ‘Persoana::Persoana’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any help in the right direction is appreciated

class Persoana{
    int CNP;
    string Nume, Prenume, Nastere, Domiciliu, Gen;

public:
    Persoana(int cnp, string nume, string prenume, string nastere, string domiciliu, string gen){
    set_CNP(cnp);
    set_Nume(nume);
    set_Prenume(prenume);
    set_Nastere(nastere);
    set_Domiciliu(domiciliu);
    set_Gen(gen);}
};

class Student: public Persoana{
    int Id, An;
    string Facultate;

public:
    Student(int id, int an, string facultate):Persoana(cnp, nume, prenume, nastere, domiciliu, gen){
        set_Id(id);
        set_An(an);
        set_Facultate(facultate);}
};


int main()
{
    //Persoana eu(123456789,"Nal","Vamal","2.03.2005","Centru","M");
    Student el(321,2,"A");
    return 0;
}

>Solution :

In your Student constructor you try to initialize the parent Persoanaobject, by using its constructor and passing the arguments needed.

But those argument variables aren’t defined anywhere in the Student class or its constructor. The arguments you pass just doesn’t exist anywhere.

One way to solve the problem is to pass the same arguments to the Student constructor, which is then passed on to the Persoana constructor:

class Student: public Persoana{
    // ...
public:
            
    Student(// First the Student-specific arguments
            int id, int an, string facultate,
            // Then the Persoana-specific arguments
            int cnp, string nume, string prenume, string nastere,
            string domiciliu, string gen)
        : // Initialize the base class object
          Persoana(cnp, nume, prenume, nastere, domiciliu, gen),
          // And initialize the Student object variables
          Id(id), An(an), Facultate(facultate)
    {
    }

    // ...
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading