R
richard_l
Hello All,
Please see attached example code.
I'm writing a program whereby I would like to reference an object from
another object.
For example I have an object called Value and I have created a
reference to that object in the class Container by using Value& m_Val.
At present the only way I can initialise this object is by initialising
the object on creation eg.
Container (Value& Val) : m_Value(Val) { ... }
Is there another way of initalizing this reference whithout using this
method?
Many thanks in advance,
Richard Latter
Code....
#include <iostream>
using namespace std;
class Value
{
public:
int& m_nVal;
public:
Value (int& nVal) : m_nVal(nVal) { }
public:
~Value () { }
};
class Container
{
public:
Value& m_Value;
Container (Value& Val) : m_Value(Val) { }
public:
~Container () { }
};
int main (void)
{
int i=5;
int& ri=i;
Value val(i);
Value &Vref=val;
Container cont(val);
cout << "i = " << i << endl;
cout << "Value = " << val.m_nVal << endl;
cout << "Container = " << cont.m_Value.m_nVal << endl;
i = 20;
cout << "i = " << i << endl;
cout << "Value = " << val.m_nVal << endl;
cout << "Container = " << cont.m_Value.m_nVal << endl;
return (0);
}
Please see attached example code.
I'm writing a program whereby I would like to reference an object from
another object.
For example I have an object called Value and I have created a
reference to that object in the class Container by using Value& m_Val.
At present the only way I can initialise this object is by initialising
the object on creation eg.
Container (Value& Val) : m_Value(Val) { ... }
Is there another way of initalizing this reference whithout using this
method?
Many thanks in advance,
Richard Latter
Code....
#include <iostream>
using namespace std;
class Value
{
public:
int& m_nVal;
public:
Value (int& nVal) : m_nVal(nVal) { }
public:
~Value () { }
};
class Container
{
public:
Value& m_Value;
Container (Value& Val) : m_Value(Val) { }
public:
~Container () { }
};
int main (void)
{
int i=5;
int& ri=i;
Value val(i);
Value &Vref=val;
Container cont(val);
cout << "i = " << i << endl;
cout << "Value = " << val.m_nVal << endl;
cout << "Container = " << cont.m_Value.m_nVal << endl;
i = 20;
cout << "i = " << i << endl;
cout << "Value = " << val.m_nVal << endl;
cout << "Container = " << cont.m_Value.m_nVal << endl;
return (0);
}