What am I doing wrong with this inheritance

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.
You can't get at the English teacher (sad sign of the times!) - he's private.
what do you mean by private?
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.
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
Topic archived. No new replies allowed.