0
class Complex
{
private:
    float real, imaginary;
public:
    Complex(float real, float imaginary)
    {
        this->real = real;
        this->imaginary = imaginary;
    }
    float getReal() const
    {
        return this->real;
    }
    float getImaginary() const
    {
        return this->imaginary;
    }
    Complex operator+(Complex other)
    {
        return Complex(this->real + other.real, this->imaginary + other.imaginary); // Here I can access other class' private member without using getter methods.
    }
};

int main()
{
    Complex first(5, 2);
    Complex second(7, 12);
    Complex result = first + second; // No error
    std::cout << result.getReal() << " + " << result.getImaginary() << "i"; // But here I have to use getters in order to access those members.
    return 0;
}

Why I am getting access to a class' private members from another class? I thought I have to use getters to access other class' private members. But it turns out, that if I call it from another class, it no longer requires those getters and I can access them directly. But this is not possible outside of that class.

Xited
  • 69
  • 7
  • 4
    "_Here I can access other class' private member without using getter methods._" But you aren't accessing other class' members. It's class `Complex`, accessing members, of class `Complex`. What, exactly, is the problem here? – Algirdas Preidžius Jan 10 '20 at 14:01
  • 1
    The fundamental problem is distinguishing between another class and another object. `private` is private to the *class*, not the object. Both `*this` and `other` are objects of class `Complex`. – Martin Bonner supports Monica Jan 10 '20 at 14:27

2 Answers2

2
 Complex result = first + second;

This invokes operator+ for Complex class, operator itself is part of Complex class so it has access to all members of this class, even for other instance passed as an argument.

std::cout << result.getReal() << " + " << result.getImaginary() << "i";

operator<< is not defined for your class, so you have to pass 'something printable' to cout's << operator. You cannot simply write result.real because it is private in this context, that is, outside of Complex class.

Hawky
  • 441
  • 1
  • 3
  • 10
2

It's not another class; it's another instance, and functions in an A can access private members of another A. That's just how it works. Otherwise it would be impossible to do things like you've done, and we need to be able to do those things.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055