Just for completeness (I was editing my last post when you replied but the server bombed out on me)...
The
friend alternative, which could be useful if you have a more complex class and don't want to provide a load of accessor functions would look like this:
#include <iostream>using namespace std;class variable{public: variable(): Val(0) {}; const variable& operator =(int val);private: friend ostream &operator<<(ostream &os,const variable &v); int Val;};const variable& variable::operator =(int val){ Val = val; return *this;}ostream &operator<<(ostream &os,const variable &v){ return os << Val;}int main(){ variable a,b,c; a = 5; b = 10; c = 20; cout << "A = " << a << endl; cout << "B = " << b << endl; cout << "C = " << c << endl; system("pause");}
That is certainly one of the less evil uses of a friend function although generally you would want to provide accessors for other uses anyway and it is best to use the first approach unless it is impractical or compromises your encapsulation in some way.
And since I am in a
very good mood indeed today, I won't criticise your use of system("pause"); [smile]. I would normally though since it is not good practice.