Reputation: 15
I have two C++ functions in a class:
void Attribute::setIndex(int inIndex) {
if (inIndex < 0) {
index = 0;
}
else if (inIndex >= MAX_NUM_ATTRIBUTES) {
index = MAX_NUM_ATTRIBUTES - 1;
}
else {
index = inIndex;
}
}
and
int Attribute::getValueWithinRange(int value) {
value = setIndex(value);
return value;
}
The second function is supposed to use setIndex to set 'value' to the correct number and return it. However, since the first function is a void function, i cannot simply pas the value in the way i did above. Should i do pass by reference or are there any suggestions? Thank you very much.
Upvotes: 1
Views: 170
Reputation: 1649
I would like just to note, that if you are learning C++, you should try to learn model cases first, sometimes rushing examples is not the best way, but there we go:
Change the setIndex to return int, my favorite;
int Attribute::setIndex(int inIndex)
{
if (inIndex < 0)
{
index = 0;
}
else if (inIndex >= MAX_NUM_ATTRIBUTES)
{
index = MAX_NUM_ATTRIBUTES - 1;
}
else
{
index = inIndex;
}
return index;
}
int Attribute::getValueWithinRange(int value)
{
value = setIndex(value);
return value;
}
Change the getValueWithinRange to return index, both methods are in one class, they share the access to index;
int Attribute::getValueWithinRange(int value)
{
setIndex(value);
return index;
}
Giving it reference would work, but you can not set reference to null unless using a trick and it would require unnecessarily another method, so pointer makes it less messy:
int Attribute::setIndex(int inIndex, int* ret_index = nullptr)
{
if (inIndex < 0)
{
index = 0;
}
else if (inIndex >= MAX_NUM_ATTRIBUTES)
{
index = MAX_NUM_ATTRIBUTES - 1;
}
else
{
index = inIndex;
}
if (ret_index != nullptr) *ret_index = index;
return index;
}
int Attribute::getValueWithinRange(int value)
{
int retvalue;
setIndex(value); // use it like this when returning value is not needed
setIndex(value, &retvalue);
return retvalue;
}
Upvotes: 1