I decided to try something out of curiosity to see how it would work. I got it into my head to see if one object of a class could access the private variables of another object of the same class. Apparently it can, if this program is any indicator:
#include <iostream>
using namespace std;
class Colour
{
private:
int var;
public:
void setVar(int x)
{
var = x;
}
int getVar() const
{
return var;
}
int getOtherVar(Colour col) //steals the private var of another Colour object
{
return col.var;
}
};
int main()
{
Colour green;
Colour red;
green.setVar(54);
red.setVar(32);
cout << "Green is " << green.getVar() << endl;
cout << "Red is " << red.getVar() << endl;
cout << "Green thinks Red is " << green.getOtherVar(red) << endl;
return 0;
}
I was kind of expecting it to fail in a way where every unique instance of a class has access only to its own private members. I did some research and found out that privacy is a class-specific thing, not an instance-specific thing.
Anyways, I decided to experiment further and found something a bit confusing. I edited the implementation for getOtherVar()
and turned it into this:
int getOtherVar(Colour col) const
{
col.var = 67;
return col.var;
}
I figured that if objects can access each others members, shouldn't the const
keyword protect other objects of the same class from change as well? It doesn't and I have no clue why.