felknight
felknight

Reputation: 1423

Passing to a function argument a reference member variable

Is it possible to pass to a function that has a reference argument a variable member of a class?

Let's say

class Foo
{
 int A;
 int B;
}

void foo(int& a)
{
    a++;
}

void main()
{
    Foo f;
    foo(f.A);
}

Is this possible?

Upvotes: 2

Views: 65

Answers (1)

Yes, this is possible, and it works exactly how you expected it to.

But note that in your existing code, A and B are private (by default). That means nothing outside the class can access them, for any reason (which includes using them as references).

Declare them as them public:

class Foo
{
public:
    int A;
    int B;
};

or change Foo to a struct:

struct Foo
{
    int A;
    int B;
};

Upvotes: 3

Related Questions