I'm carrying this around in my signature at the moment, because I found the statement somewhat amusing:
class `Matt' is implicitly friends with itself.
(Of course, the class wasn't really called Matt. I like the look of my own name. Perhaps).
Preamble aside; the more I think about that, the more I wonder. The statement came about, because I made a class, I wanted the class to blueprint objects that would create more alike (of the same class) objects, and I didn't want to have to use accessor methods to set certain properties for the created objects. So I figured, incorrectly, that I'd need to make the class its own friend. My logic being, that private members are innaccessible from outside an object, unless whatever is accessing the object's private member is a friend of the object.
Of course, the message class `Class' is implictly friends with itself, proves that logic incorrect; the private members of an object seem to be accessible between objects of the same class. This is different to how I've always perceieved 'private'. I won't say I went from Java to C++, (I first used C++ before I first used Java), but, I've definately spent more time developing in Java than C++, and in Java, if I'm not mistaken, private means object-private not class-private.
I actually want to ask if this is complier specific (I'm using g++) As I understand C++, it's the compiler that checks access priviledges between objects/members, and then the compiled program just does what it does.
So, is this true: "the private members of an object are only accessible to this object, and to any other object of the same class", is this a G++ only thing, or is there any room for debate?
Example code follows, it should show what I'm talking about..
#include <iostream>
class Test
{
private:
int myvalue;
public:
Test(void);
void affect_alike(Test * what);
int get_value(void);
};
Test::Test(void):myvalue(7)
{
cerr << "Created test object" << endl;
};
void Test::affect_alike(Test * what)
{
what->myvalue = 100;
}
int Test::get_value(void)
{
return myvalue;
}
int main(void)
{
Test * test1 = new Test();
Test * test2 = new Test();
cout << endl;
cout << "T1: " << test1->get_value() << endl << "T2: " << test2->get_value() << endl;
test1->affect_alike(test2);
cout << "T1: " << test1->get_value() << endl << "T2: " << test2->get_value() << endl;
cout << "Done" << endl << endl;
return 0;
}
results in:
T1: 7
T2: 7
T1: 7
T2: 100
Done