Reputation: 53
I have a simple class test:
class test{
public:
test(){};
test(int &input){a=input;};
~test (){};
int a;
};
Given that the constructor parameter is called by reference, i had expected that i would be able to manipulate the reference members from outside the calss but this is not the case:
int _tmain(int argc, _TCHAR* argv[]){
int c=10;
test t1(c);
c=20;
int d=t1.a;;}
d here gives the original value of 10 rather than 20. Why is it the case and how can you change the constructor to be able to manuipulate a through c.
THank you
Upvotes: 0
Views: 311
Reputation: 103751
The member needs to be a reference, and you need to initialize it in the initialization list, like this:
class test{
public:
test(int &input)
:a(input)
{}
int &a;
};
You can't assign it in the body because all references need to be initialized. By the time you get to the body, it's too late, initialization has already happened. You also can't have your default constructor, because you have to have something to initialize the reference to, and without a parameter, that means you'd either have to use a global, another int member, or create a new int dynamically(very bad idea).
Upvotes: 2
Reputation: 131887
This is not a problem of the constructor, but the problem of the member variable. It's int
, which is a completely unrelated, new int
. To have it reference something, use int&
. Then, you also can't have a default constructor and you have to use the initialization list:
class test{
public:
test(int &input):a(input){}
int& a;
};
Upvotes: 4