Rindo789
Rindo789

Reputation: 21

Passing an class type as a constructor argument C++

I am trying to learn c++ when I stumbled on a error. I have this class that inherits from the class PERSON.

#include <iostream>
#include <string>

class PERSON
 {
 private:
    std::string name;
    bool sex;
 public:
        PERSON(std::string name, bool sex) : name(name) , sex(sex){};
       //methods
};

class TEACHER:  public PERSON
{
private:
    std::string title;
public:
    TEACHER(std::string name, bool sex, std::string title) : PERSON(name,sex), title(title){};
//methods
};

Now the problem starts when I need to place this class TEACHER inside a constructor to create a class CLASSROOM, to pass them as arguments.

class CLASSROOM : public TEACHER
{
private:
    std::string name;
    TEACHER lecturer;
    TEACHER s_teacher;
public:
    CLASSROOM(std::string name, TEACHER lecturer , TEACHER s_teacher){};
    //methods
};

When I compile this its shows an "error no matching function for call to 'TEACHER::TEACHER()'" and I don't know how to initialize the CLASSROOM constructor. I tried few things like initializing the constructor as I would with the other constructors but the same error shows up.

Upvotes: 0

Views: 1363

Answers (2)

Jeune Prime Origines
Jeune Prime Origines

Reputation: 249

A CLASSROOM is not a kind of TEACHER so I think don't really want to derive CLASSROOM class from TEACHER class.

Once the above is corrected, you can then write the constructor as follows:

class CLASSROOM 
{
private:
    std::string name;
    TEACHER lecturer;
    TEACHER s_teacher;
public:
    CLASSROOM(std::string name, TEACHER lecturer , TEACHER s_teacher):  
       name(name),
       lecturer(lecturer),
       s_teacher(s_teacher) {};
    //methods
};

Upvotes: 1

Tfry
Tfry

Reputation: 194

You problem is here:

class CLASSROOM : public TEACHER

You told the compiler that your CLASSROOM is a TEACHER, and the error message just means that you have no so-called "default constructor" for a TEACHER (only one that takes name, sex, and title as arguments).

Of course, almost certainly, you don't want CLASSROOM to inherit from TEACHER. A classroom may have one or more teachers inside it, but it is not a teacher.

Upvotes: 0

Related Questions