Hi all...

For a project I have to create a small program that adds class data using templates. I've completed the project, but the output is not expected for the last cout in main.

Here is the code:

#include <iostream>

using namespace std;

template <class T>
T add (T x, T y)
	T summary;
	summary = x + y;
	return summary;

class Homework
		string className;
		string assignment;
		int estimatedTime;
		friend ostream& operator << (ostream& out, Homework &info);
		void setValues(string, string, int);
		Homework operator + (Homework &h);

ostream& operator<<(ostream& out, Homework &info)
	out << "Course:  " << info.className << endl;
	out << "Assignment:  " << info.assignment << endl;
	out << "Time:  " << info.estimatedTime << " minutes" << endl;
	out << "--------------------------------------------" << endl;
	return (out);

void Homework::setValues(string name, string assign, int time)
	className = name;
	assignment = assign;
	estimatedTime = time;

Homework Homework::operator + (Homework &h)
	Homework temp;
	temp.className = "All Courses";
	temp.assignment = "All Assignments";
	temp.estimatedTime = h.estimatedTime + h.estimatedTime;
	return temp;

void userComments()
	cout << "This program uses a class and overload operators.\n\n" << endl;

int main()
	int a = 65, b = 90, c, num;
	double d = 45.25, e = 120.5, f;
	Homework h, i, j;
	h.setValues("English","Read Chapter 11", 75);
	i.setValues("History","Read Chapter 22", 45);
	c = add (a,b);
	f = add (d,e);
	j = add (h,i);
	cout << "Result of integer addition:  " << c << endl;
	cout << "Result of double addition:  " << f << endl;
	cout << "Result of homework addition:  " << j << endl;
	cout << "Press 1 to exit";
	cin >> num;
	while(num != 1)
		cout << "Must press 1 to exit program - please enter 1: ";
		cin >> num;

I don't understand what is happening to h when it is sent to the overloaded >> operator...seems like it is just going "poof" and only i is being added in the template.

Thanks in advance for any pointers you can/will give me.


on line 47 you have

temp.estimatedTime = h.estimatedTime + h.estimatedTime;

all this is doing is adding the term h.estimatedTime to itself effectively doubling it. if you want to add the first and second terms you can do

temp.estimatedTime = this->estimatedTime + h.estimatedTime;

this will add both terms together if the data is public. if you want to keep the data private i would suggest writing some accessor functions like int GetEstimatedTime() {return estimatedTime } so you can get the private data.

No need (for this project) to keep the data private.

This worked, thank you very much.

I need to go back and study "this->". I'm not 100% what it is doing.

Again, thank you very much.

the this pointer is the holder of what class is holding the function. that way you can call other function within a function using this->

This question has already been answered. Start a new discussion instead.