Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Confusion over access modifiers

Status
Not open for further replies.

maluk

Programmer
Oct 12, 2002
79
SG
Hello ppl!

Can you tell me why the code below works?
Why can a class access the private variables of the same class even though they are different instances?

Code:
class Complex
{
public:
    Complex();
    Complex(double r, double i);
    Complex add(Complex c);
private:
    double real;
    double imaginary;
};

Complex::Complex()
{
    ;
}

Complex::Complex(double r, double i)
{
    real = r;
    imaginary = i;
}

Complex Complex::add(Complex c)
{
    return (Complex(real + c.real, imaginary + c.imaginary));
}

int main()
{
    Complex c1(1, 2);
    Complex c2(3, 4);
    Complex c3 = c1.add(c2);
}

As you can see real and imaginary are private. But why can it be accessed?

Rome did not create a great empire by having meetings, they did it by
killing all those who opposed them.

- janvier -
 
Access modifiers work across all instances of a particular class, not just for one instance, particularly for situations like the one you posted.
 
Indeed, if everytime you needed access to the private members of a seperate instane of the class you needed to use the accessors/inspectors it all classes would be a lot larger needlessly. The idea is that every "MyClass" knows what goes in a "MyClass" and was written by the same people/persons, so to save LOC and make more elegent solutions. Often times you see the constructor of a class use the mutator for a particular varible if there is data checking that has to happen on that variable.
 
Some additions: member access is class (not an object) level notion. All class members can see each others, private or not. Abstract class has no objects, but its members access properties are relevant...
But look out: this class Complex is a black hole. We can't access values of its objects any way, and its successors can't. We must declare (and define;) some operators before use it...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top