Having an issue figuring out my problem

So basically my code should output "1" becasue there is only one cs400. I can only get my code to output 1 if I put cs400 first where math195 currently is. When looking through the debugging I noticed that my pointers were not saving how I thought they should. I thought they would work something like this: math195->cs350->cs400->cs310->GenEd (s7->s3->s5->s1->GenEd) but in reality its end up like cs350->SCourses, cs400->SCourses. Is there something wrong with me doing s1 = *s2 thats not correctly working? Hopefully my question isnt too confusing.

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <string>

using namespace std;


class SCourses {
public:

	virtual int count_cs400() { return  0; }

};

class GenEd : public SCourses  {
public:

	int count_cs400() { return 0; }
};

class cs310 : public SCourses {
public:
	SCourses s1;
	cs310(SCourses *s2) { s1 = *s2; }

	int count_cs400() { return s1.count_cs400(); }
};

class cs350: public SCourses {
public:
	SCourses s3;
	cs350(SCourses *s4) { s3 = *s4; }

	int count_cs400() { return s3.count_cs400(); }
};

class cs400: public SCourses {
public:
	SCourses s5;
	cs400(SCourses *s6) { s5 = *s6; }

	int count_cs400() { return 1 + s5.count_cs400(); }
};

class Math195: public SCourses {
public:
	SCourses s7;
	Math195(SCourses *s8) 
	{ s7 = *s8; }

	int count_cs400() { return s7.count_cs400(); }
};


int main() {
	SCourses* sl = new Math195(new cs350(new cs400(new cs310(new GenEd()))));

	cout << "The student took CSCI400 this many times: " << sl->count_cs400() << endl;
	system("pause");

}
Those numbers are just course numbers.
The problem is that you're "slicing" your objects when you copy them into the data members, because those data members are all SCourses objects. When you're doing, for example, s1 = *s2, s1 is nothing more than an SCourses object, and calling s1.count_cs400() is just going to return zero.

If you want to use polymorphism, you'll need to use pointers to SCourses, not objects. You'll also need to think about where you need to make your methods virtual.
Topic archived. No new replies allowed.