Search code examples
c++inheritanceconstructorsubclassdefault-constructor

Subclass declares "no appropriate default constructor available"


I made a class with a default constructor and a subclass. When I try to create an instance of the subclass using a default constructor, I get the errors C2512 (no appropriate default constructor available) and E0289 (no instance of constructor "Faculty::Faculty" matches the argument list).

#include <string>
#include <memory>

using namespace std;

class Person {
protected:
    string name;
public:
    Person() {
        setName("Belethor");
    }

    Person(const string& pName) {
        setName(pName);
    }

    void setName(const string& pName) {
        name = pName;
    }
};

class Faculty : public Person {
private:
    string department;
public:
    Faculty(const string& fname, const string& d) : Person(fname) {
        department = d;
    }
};

#include <iostream>
#include "college.h" 
#include <memory>

using namespace std;

int main()
{
    shared_ptr<Faculty> prof = make_shared<Faculty>();
    return 0;
}

Does class Faculty not inherit the default constructor defined in class People?


Solution

  • As noted in comments, no, you have explicitly stated that Faculty has only one constructor and it takes two arguments. Now, you could provide default values for those arguments, though I'm not sure what values would make sense as defaults in a case like this.

    Your classes also need to be followed by a semicolon, and you can initialize department in your member initialization list.

            Faculty(const string& fname, Discipline d) 
            : Person(fname), department(d) 
            { }