bn4365
bn4365

Reputation: 31

Passing reference as object in C++?

I know that C++ references are not objects, but seems that I can pass references as objects.

In the code below, v1 and v2 are references, and are assigned as double &v1 = x1 through the constructor. Then, while calling from foo(), should I have bar(double &) or bar(double)? Based on double &v1 = x1, shouldn't there be bar(double)?

This looks confusing to me. Can someone explain it?

#include <iostream>

class FooBar
{
private:
    double &v1, &v2;
public:
    FooBar(double &, double &);
    void foo();
    void bar(double &);
};

FooBar::FooBar (double &x, double &y): v1(x), v2(y) {}

void FooBar::foo()
{
    bar(v1);
    bar(v2);
}

void FooBar::bar(double &x)
{
    std::cout << x << "\n";
}

int main()
{
    double x1 = {0.5}, x2 = {1.5};
    FooBar f(x1, x2);
    f.foo();
    return 0;
}

Upvotes: 0

Views: 100

Answers (1)

FrankS101
FrankS101

Reputation: 2135

Then while calling from foo(), should I have bar(double &) or bar(double)? Based on double &v1 = x1, shouldn't there be bar(double)?

In this case it doesn't matter, v1 is a reference and if you change it inside of bar, the variable that was used to initialized it will also change, regardless if the parameter of bar is declared as double or double&.

Have in mind that a reference is like a synonym to a variable. Even though the C++ standard does not specify how a compiler must implement references, every C++ compiler I know implements references as pointers. So basically, you are passing the memory address of the variable to the function anyway.

Upvotes: 1

Related Questions