Passing in an address into a class function

Sep 21, 2018 at 5:01am
I'm doing a grocery store code and we're given a skeleton. I get that an address is passed in since there is a '&' but how would I assign that value to the variable? I don't want to assign the address... would I use an asterisk (_taxRate = *tax;)?

1
2
3
4
  void GroceryInventory::setTaxRate(const float& tax){
    _taxRate = tax;
}
Sep 21, 2018 at 5:38am
In this context, the & does not mean address but rather reference.

Maybe someone told you that references are "addresses", but that analogy is harmful. Actually, references follow quite subtle and complicated rules, but a better analogy is that references are aliases for existing values.

In this case, since the formal parameter tax is just another name for some constant float variable, saying _taxRate = tax assigns the value, just like tax was the variable itself and not a reference to it.

From a design standpoint, there is no point in passing the argument by constant reference. In this case, it is very slightly preferable to pass by value.
Last edited on Sep 21, 2018 at 6:22am
Sep 21, 2018 at 5:48am
references as the above reply says are actually another name for the same variable,
a new variable uses the same memory that was being used by the passed variable on the stack
simple put not to confuse you more,you can directly use it like this


void GroceryInventory::setTaxRate(const float& tax)
{
_taxRate = tax;
}

int main()
{
const float lnFloatVar = 5.5;
GroceryInventory lcGroceryInventory;
lcGroceryInventory.setTaxRate(lnFloatVar);
}
Sep 21, 2018 at 7:01am
closed account (9G3v5Di1)
mbozzi I've sent you a private message
Sep 22, 2018 at 1:18am
Thank you both!
Topic archived. No new replies allowed.