I have two classes, Foo and Bar. Bar maintains a reference to Foo, and has methods that call methods in Foo to change its state. The code is shown below.
class Foo
{
private:
double m_value;
public:
void setValue(double value) {
this->m_value = value;
};
double getValue() {
return this->m_value;
};
};
class Bar
{
private:
Foo& m_foo;
public:
Bar() : m_foo(Foo()) {
};
void setFooValue(double value) {
m_foo.setValue(value);
};
double getFooValue() {
return m_foo.getValue();
};
};
The problem arises when I try to access the value of foo after setting it, as below:
Bar bar;
bar.setFooValue(10000.0);
double value = bar.getFooValue();
std::cout << "Foo value is: " << value << std::endl;
Which outputs Foo value is -9.25596e+061
. It appears the memory has become corrupt - why? I understand that not storing m_foo as a reference (i.e. using Foo m_foo;
) will fix the issue, however I don't understand why this is either.
More puzzling still is that the code above works as desired when running in release mode.
I am using Visual Studio 2010 to compile.
Many thanks in advance!