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?
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 -
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 -