Here How can I inherit string a, string b, string c, int d, string e, string f into my Student class and add int r, string fs with them?
Here How can I inherit string a, string b, string c, int d, string e, string f into my Teacher class and add string subject with them?
class Person{
public:
string name;
string level;
string group;
int age;
string phone;
string gender;
Person(string a, string b, string c, int d, string e, string f){
name = a;
level = b;
group = c;
age = d;
phone = e;
gender = f;
cout << "Student name: " << name << endl;
cout << "Study Position: " << level << endl;
cout << "Group: " << group << endl;
cout << "Age: " << age << endl;
cout << "Phone: " << phone << endl;
cout << "Gender: " << gender << endl << endl;
}
};
class Student: public Person{
public:
int roll;
string favoriteSubject;
Student(int r, string fs){
roll = r;
favoriteSubject = fs;
}
};
class Teacher: public Person{
public:
string subject;
Teacher(string s){
subject = s;
}
};
CodePudding user response:
If I understood correctly, simply receive the arguments as parameters of your child class constructor, and send it to the parent's constructor:
class Teacher: public Person{
public:
std::string subject;
Teacher(
std::string a,
std::string b,
std::string c,
int d,
std::string e,
std::string f,
std::string s
) : Person(a, b, c, d, e, f), subject(s) { }
};
CodePudding user response:
I am interpreting the question as "How can I avoid repeating every single constructor parameter of the base in derived class constructors".
If that's the case, then you can approximate this by using structs representing the set of params for the construction of each class:
#include <string>
using namespace std;
struct PersonParams {
string a;
string b;
string c;
int d;
string e;
string f;
};
struct StudentParams {
PersonParams p;
int r;
string fs;
};
struct TeacherParams {
PersonParams p;
string s;
};
class Person{
public:
string name;
string level;
string group;
int age;
string phone;
string gender;
Person(const PersonParams & params) {
// redacted...
}
};
class Student: public Person {
public:
int roll;
string favoriteSubject;
Student(const StudentParams & params)
: Person(params.p),
roll(params.r),
favoriteSubject(params.fs) {}
};
class Teacher: public Person {
public:
string subject;
Teacher(const TeacherParams& params)
: Person(params.p),
subject(params.s) {}
};
int main() {
Teacher mr_dude({
{"Mr. Dude", "lvl3", "grp_a", 43, "555-1234", "M"},
"Maths"
});
}