In C++, we can define a variable by reference like:
int foo = 3;
int &bar = foo;
Then, the following code
cout << foo << " " << bar;
will print
3 3
because the "value" of bar is tied to the value of foo by reference(&). I'm wondering, is there a way to tie the value of "bar" to two variables? Say I have three variables: geddy, neil, and alex, and I want neil to always equal alex + geddy. Is there a way two write something like:
int alex = 4;
int geddy = 5;
int &neil = alex + geddy;
So that neil will return 9? Then, if I change alex to 7, neil will return 12?
Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. The following example shows how arguments are passed by reference.
Not in C. In C++ you could do it with references. In C, a variable is by definition a unique address.
A reference variable is a variable that points to an object of a given class, letting you access the value of an object. An object is a compound data structure that holds values that you can manipulate. A reference variable does not store its own values.
A reference assignment statement redirects either a reference variable or an array variable. A reference variable is a pointer to an object. An array variable points to a set of reference variables, which points to a set of objects.
No, not really. You could make a function or functor though:
int alex = 4;
int geddy = 5;
auto neil = [&]() { return alex + geddy; };
std::cout << neil() << "\n";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With