Hi, I'm taking a class on C++ and we just went over classes and objects. We have a homework assignment due and I was wondering if someone could check over my work because some of this class stuff is hard to wrap my head around.

Here's the homework assignment (it's a diagram I have to follow):
http://i28.photobucket.com/albums/c216/aldodesigns/class.jpg
The first question says: Write a class declaration based on the diagram and my code for that is,

#include <iostream>
using namespace std;

class money
{
private:
	int dollars;
	int cents;
	void adjust(int, int);
public:
	money(int d = 0, int c = 0) : dollars(d), cents(c) {}

	int getDollars() const;
	int getCents() const;
	void setDollars(int d);
	void setCents (int c);
	void print(ostream & o)const;
	operator + (const money rhs) const;
};

The second question asks for a default constructor that sets the dollar and cent values to 0, this is my code:

money(int d = 0, int c = 0) : dollars(d), cents(c) {}

Lastly, it asks for the code for the method, print

void money::print(ostream & o)
{
        o << "$" << d << ". " << setfill('0') << setw(2) << c << endl;
return;
}

Welcome to DaniWeb!

Looks good to me. You should write a main function to instantiate the class and call the print function. Does it compile without errors and produce the correct output? If so then I think you're good to go!

Dave

operator + (const money rhs) const;

class objects should generally be passed as reference. Use:

operator + (const money &rhs) const;

>>operator + (const money rhs) const

I guess no one else saw this, but you need to specify the return type for any function.
What should the return type of operator+ should be, in other words, what should the
addition operation return for this class?

What should the return type of operator+ should be, in other words, what should the
addition operation return for this class?

While it's not the rule of the thumb, but operators should generally return the new value, for chain assignment.

money &operator + (const money &rhs) const //Again reference

EDITT: Thanks for noticing firstPerson.

Edited 6 Years Ago by nbaztec: n/a

While it's not the rule of the thumb, but operators should generally return the new value, for chain assignment.

money &operator + (const money &rhs) const //Again reference

arghh, it was a question for OP, so he can think. It wasn't a question for me.

arghh, it was a question for OP, so he can think. It wasn't a question for me

:P My post was for OP.
My bad for giving it out. :)

EDIT: Now it should be clearer after Editing.

Edited 6 Years Ago by nbaztec: n/a

This article has been dead for over six months. Start a new discussion instead.