What am I doing wrong with this inheritance
Nov 3, 2019 at 10:58pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include <iostream>
using namespace std;
class Teacher {
public :
Teacher() {
cout << "Hey Guys, I am a teacher" << endl;
}
string collegeName = "Stark State" ;
string mainSub;
string name;
};
//This class inherits Teacher class
class MathTeacher : public Teacher {
public :
MathTeacher() {
cout << "I am the Math Teacher" << endl;
}
string mainSub = "Math" ;
string name = "Mrs. Borton" ;
};
class EnglishTeacher : public Teacher {
EnglishTeacher() {
cout << "I am the English Teacher" << endl;
}
string mainSub = "English" ;
string name = "Mr. Morrosko" ;
};
int main() {
MathTeacher obj;
EnglishTeacher obj2;
cout << "Name: " << obj.name << endl;
cout << "College Name: " << obj.collegeName << endl;
cout << "Main Subject: " << obj.mainSub << endl;
cout << "----------------------------------------------------------------" << endl;
cout << "Name: " << obj2.name << endl;
cout << "College Name: " << obj2.collegeName << endl;
cout << "Main Subject: " << obj2.mainSub << endl;
system("pause" );
return 0;
}
Not sure why the obj2 isn't working like the first one is.
Nov 3, 2019 at 11:14pm UTC
You can't get at the English teacher (sad sign of the times!) - he's private.
Nov 3, 2019 at 11:15pm UTC
what do you mean by private?
Nov 3, 2019 at 11:18pm UTC
Not
public:
See line 14 in your Maths teacher's class. Default access in a class is private, so without making the constructor public you will have difficulty instantiating the English teacher.
Nov 3, 2019 at 11:27pm UTC
You shouldn't duplicate mainSub and name in the derived classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include <iostream>
#include <string>
using namespace std;
class Teacher {
private :
string collegeName = "Stark State" ;
string mainSub;
string name;
public :
Teacher(string sub, string name) : mainSub(sub), name(name) {
cout << "Teacher ctor\n" ;
}
void print() {
cout << "\nName : " << name << '\n' ;
cout << "College Name: " << collegeName << '\n' ;
cout << "Main Subject: " << mainSub << '\n' ;
}
};
class MathTeacher : public Teacher {
public :
MathTeacher(string name) : Teacher("Math" , name) {
cout << "MathTeacher ctor\n" ;
}
};
class EnglishTeacher : public Teacher {
public :
EnglishTeacher(string name) : Teacher("English" , name) {
cout << "EnglishTeacher ctor\n" ;
}
};
int main() {
MathTeacher m("Mrs. Borton" );
EnglishTeacher e("Mr. Morrosko" );
m.print();
e.print();
}
Last edited on Nov 3, 2019 at 11:29pm UTC
Topic archived. No new replies allowed.