This is interesting, we can actually change the private variable of a class from main.
class c
{public:
c(int x = 0):n(x) {}
int & GetRN() { return n;}
private:
int n;
};
int main()
{
c x;
int & a = x.GetRN();
cout << "a = " << a << endl;
cout << "x.GetRN() = " << x.GetRN() << endl;
a = 5;
cout << "a = " << a << endl;
cout << "x.GetRN() = " << x.GetRN() << endl;
return 0;
}
And the output is:
a = 0 x.GetRN() = 0 a = 5 x.GetRN() = 5
To prevent this, I have tried to use "const" keyword in GetRN() accessor method , so that if a user does int &a = x.GetRN(), he/she won't be able to change the private variable "n" from outside the class.
class c
{public:
c(int x = 0):n(x) {}
int & GetRN() const { return n;}
private:
int n;
};
int main()
{
c x;
int a = x.GetRN();
cout << "a = " << a << endl;
cout << "x.GetRN() = " << x.GetRN() << endl;
a = 5;
cout << "a = " << a << endl;
cout << "x.GetRN() = " << x.GetRN() << endl;
return 0;
}
Error:
t.cpp: In member function 'int& c::GetRN() const': Line 4: error: invalid initialization of reference of type 'int&' from expression of type 'const int' compilation terminated due to -Wfatal-errors.
If I remove const from line 4, everything goes well and fine as shown in my first code. Does it mean that we can't return a reference to a variable when the function is supposed to be "const" ?
This post has been edited by indyarocks: 25 May 2012 - 06:30 PM

New Topic/Question
Reply



MultiQuote









|