#include<iostream>
usingnamespace std;
class TypeCheck
{
private:
int var;
int *varptr;
constint varconst;
constint *varptrconst;
int &ref; // Here i have doubt
public:
TypeCheck(int a): varconst(5),ref(a)
{
cout<<"Do Nothing";
}
void print() // Function to print value of Member variable
{
cout<<"value of var "<<var<<"\n";
cout<<"value of *varptr "<<*varptr<<"\n";
cout<<"value of vvarconstar "<<varconst<<"\n";
cout<<"value of varptrconst "<<*varptrconst<<"\n";
cout<<"value of ref "<<ref<<"\n";
}
};
int main()
{
int item = 5;
TypeCheck obj1(item); // Passing item that will be stored in TypeCheck::ref
obj1.print();
item = 10; // Why the value of TypeCheck::ref is not changed?
obj1.print();
cin>>item;
obj1.print(); //After using "cin",TypeCheck::ref has junk value. why?
cin>>item;
}
its actually a pointer
do something more like: int *ref;
and replace the TypeCheck(int a): varconst(5), ref(a)
with TypeCheck(int &a): varconst(5), ref(&a)
and the cout<<"value of ref "<<ref<<"\n";
with cout<<"value of ref "<<*ref<<"\n";
the operator & means address of
and a <type> *varName is a pointer to variables of that type which is a 1 byte variable that holds addresses
ie:
1 2 3 4 5 6 7 8 9 10 11 12 13
int *x, *y, z = 5;
x = &z; //value of x = address of z, value of *x = value of z
y = x; //value of y = address of z, value of y = value of x;
cout << *x << endl << x << endl << *y << endl << y;
/*
outputs:
address of z
5
address of z
5
*/
*y = 10; //value of z = 10
cout << endl << z; //outputs 10
You are passing the integer by value to the constructor so a inside the constructor is a copy of item in main. ref binds to a that will no longer exist after the constructor has ended so you end up with an invalid reference. Passing by reference will fix this problem.