Aaron
Aaron

Reputation: 1743

C++ setting reference variable in a class and afterwards changing

Say I have a class Foo with a reference variable of type Bar and a constructor like so:

Foo.h:

class Foo {
  public:
    Bar& m_b;

    Foo(Bar& b);
}

Foo.cpp

Foo::Foo(Bar& b) : m_b(b) {
}

And in a separate class I have:

// global 
Bar b; 
Foo f(b);

int main() {   
  b.setData();       // actually set some values...
  f.m_b.showData();  // will it show the change?
  return 0; 
}

Will the reference variable in f also have that change of data after setData() is called? I am trying this work-around because I have a class that has a reference variable (which must be set during initialization) but I need it to be globally accessible (declared before actually setting the data in Bar).

Upvotes: 0

Views: 109

Answers (2)

Luchian Grigore
Luchian Grigore

Reputation: 258608

Yes it will. A reference is just an alias. f::m_b and b are exactly the same object.

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477040

Yes. f.mb and b both refer to the same object.

Upvotes: 1

Related Questions