Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Beginner's Question on RETURN statement

Status
Not open for further replies.

saff

Technical User
Jul 14, 2002
1
0
0
TT
Hi,

I am tring to implement a time class as follows:

class HMS{
public:
// constructors
// accessors
// modifiers
HMS add (const HMS & x, const HMS & y);
HMS subtract (const HMS & x, const HMS & y);
private:
// private variables / methods
int hrs;
int mins;
int secs;

The add method adds the hours, minutes and seconds of the the two objects passed and is supposed to return the sum. However, I am wondering if this is possible...can the add method return an object of the class HMS? If so, how is it done? So far, I only know about the return statement returning integer, double , string types ect.
Please Help.

Thanks
Saff
 
You can only return primitives and pointers. If you use pointers to your class, which you should, then it will work. dl_harmon@yahoo.com
 
As a member function of HMS, you have direct access to your class member.

if you really want to use return, then write this

return *this;







 
Yeah, returning pointers is the best way to go.

Of course, if you are making a new object to hold the added values, then Add() doesn't have to return anything. "void" will do nicely.

E.g.:
Code:
HMS one;
HMS two;
HMS three;
three.Add(one, two);

If you don't want this, maybe you want friend functions? In that case, return a reference to one of the objects, modified, or a pointer to a new HMS. Just be careful about who deletes this new HMS... if it's on the heap (you created it with new), then you might have a memory leak if you don't delete it sometime later.
 
Please let me know if this is wrong:
//Code: assumes constructor of (int hrs, int mins, int secs)
HMS Add(const HMS &addto)
{
HMS temp(this.hrs+addto.hrs,
this.mins+addto.mins,
this.secs+addto.secs);
return temp;
}
 
It's not wrong. That would work, in fact.

If you catch yourself writing expressions like this, though:
Code:
HMS now(7, 14, 0);
HMS twelve_hrs(12, 0, 0);

now = now.Add(twelve_hrs);
That's an awful lot of extra typing. What if you did this?
Code:
// in the class defintion file (.cpp file)
void HMS::Add(const HMS &addto)
{
   hrs = hrs + addto.hrs;
   mins = mins + addto.mins;
   secs = secs + addto.secs;
}

// later, in a different part of the program...

HMS now(7, 14, 0);
HMS twelve_hrs(12, 0, 0);

now.Add(twelve_hrs);
Voila! Much less typing. It depends on what functionality you want. If what you typed before was exactly the functionality you want, then yeah, that'll work.

BTW, hooray to you for using
Code:
const
. ( =
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top