Today i’ve see very strange thing while working with references.
Just one simple example:
#include <iostream>
struct Base {
enum Type {
FOO = 0,
BAR = 1
};
virtual ~Base() {}
virtual Type type() const = 0;
int value_;
};
struct Foo : Base {
Foo() { value_ = 33; }
virtual Type type() const { return FOO; }
};
struct Bar : Base {
Bar() { value_ = 44; }
virtual Type type() const { return BAR; }
};
int main() {
Foo foo;
Bar bar;
Base & b = foo;
std::cout << b.type() << ", " << b.value_ << "\n";
b = bar;
std::cout << b.type() << ", " << b.value_ << "\n";
return 0;
}
What did you think output would be? I was really surprised when see it:
0, 33
0, 44
Tested on VS 2010, mingw 4.6, gcc 4.3. So, may be known secret of this magic?
References are like pointers in C++, with two important exceptions (aside from syntax):
So, when you call
b = bar, you are not reassigning the reference; you are assigning the value ofbarto the object referenced byb; in this case, you are assigning the value ofbartofoo. So, in the second line, you will have aFooobject with avalue_of44. Just what your output says.