I recently picked up Deitel's C++ How to Program 7e. I'm currently working on one of the exercises in the book and I was curious on a different way of returning a value from one of the class functions. Currently I have the following line in main:
int HeartRates::getAge(int month, int day, int year)
{
if ( month <= birthMonth )
return ( year - birthYear - 1 );
if ( month == birthMonth )
if ( day < birthDay )
return ( year - birthYear - 1 );
if ( month > birthMonth )
return ( year - birthYear );
}
int HeartRates::getMaximumHeartRate( int age )
{
return 220 - age ;
}
void HeartRates::getTargetHeartRate( int maxHeartRate )
{
cout << maxHeartRate * .5 << " - " << maxHeartRate * .85 << endl;
}
Is it possible to have the getTargetHeartRate return 2 integer values rather than having it spit out a cout? The program works as it is, but I guess what I'm trying to ask, is there a "best practice" method to use. One of the problems from learning straight out of a book is that there's no one to ask questions.
I tried changing getTargetHearRate to:
1 2 3 4 5
int HeartRates::getTargetHeartRate( int maxHeartRate )
{
return maxHeartRate * .5;
return maxHeartRate * .85;
}
But it only returned one value. Thanks in advance.
You're not returning an array, you're returning a pointer. That pointer points to 'result'.
However, as soon as the function exits, 'result' goes out of scope and is destroyed. Anything that points to it after it is destroyed is a bad pointer.
If result was allocated using new (i.e. int *result = newint[2];) would it make a difference? I think there's still problem with deleting the pointer but I better make sure :S
yes that would work, but then you'd have to remember to delete it later or else you leak memory.
I don't recommend passing ownership like that when it can be reasonably avoided. Passing memory ownership between function calls is messy and hard to manage.
The book I'm going through hasn't described structures yet, so I'm looking through some online references to it.
Arrays, pointers, and references. The last book I looked through before putting it down was horrible at explaining it. This one describes them in later chapters and was much better at explaining it. Generally I go through the book (any computer-related book) until my head spins and I acknowledge the fact that I tried to go through to quickly, then I start over. It seems to help in letting me retain the information that I digested as well as making me feel good knowing "Hey! I can do that"!
Would it also be correct in assuming that it's better to declare any variables in use by a class within the class itself rather than passing it off through main?