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

Compilation error on diamond problem(inheritance)

Why does the above code throws compilation error : No default constructor exists for class 'Person' on msvc ?

If I don’t create a default constructor in the class Person, then should I delete the constructor of Employee and Student that takes only one argument and call Employee(name,age,grade) and Student(name,age,cl) from ctor of Manager although the Base class constructor is never going to get called from Employee and Student class?

#include<iostream>
#define endl '\n'
using std::cout;

class Person {
    std::string mname;
    int mage;
public:
    //Person() = default;
    Person(const std::string& name, int age) :mname{ name }, mage{ age }{}
};
class Employee :virtual public Person {
    int msalary;
public:
    Employee(const std::string& name, int age, int sal) :Person{ name,age }, msalary{ sal }{}
    Employee(int sal): msalary { sal }{}

};
class Student : virtual public Person {
    int mclass;
public:
    Student(const std::string& name, int age, int cls) :Person{ name,age }, mclass{ cls }{}
    Student(int cls) :mclass{ cls } {}

};

class Manager :public Student, Employee {
private:

public:
    Manager(const std::string& name,int age, int salary,int cl) :Person{name,age}, Student{cl}, Employee{salary} {}
};
int main() {

    Manager manager{ "lorem",40,10000 ,10};

    return 0;
}

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

>Solution :

The cause of the problem:

Both Employee and Student have constructors that do not call the only available constructor of the base class Person (requireing name and age parameters). Therefore the compiler will attempt to use a default constuctor fo the base class which is not available.

You can handle it the following way:

  1. Decide what will be the default name and age for a Person derived class like Employee, Student.
  2. Use the defaults to construct the base, e.g.:
static inline const std::string DEFAULT_NAME = "<default_name>";
static inline const int DEFAULT_AGE = 20;
Employee(int sal) : Person(DEFAULT_NAME, DEFAULT_AGE), msalary{ sal } {}
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