When I try this code the output I get is
1 1 | 1 2
However if I get rid of the reference, i.e.
// replace
A& a_ref = b2;
a_ref = b1;
// with
b2 = b1;
the output changes to
1 1 | 1 1
and I cant find any website that explains why this happens. Can any one explain it?
#include <iostream>
struct A {
int foo;
};
struct B : public A {
int bar;
B(int x,int y) : bar(y) { this->foo=x; }
};
int main(void) {
B b1(1,1), b2(2,2);
A& a_ref = b2;
a_ref = b1;
std::cout << b1.foo << ' ' << b1.bar << " | " << b2.foo << ' ' <<
b2.bar << '\n';
return 0;
}