0

I was learning about operator overloading in C++ and came across this piece of code which is for overloading the binary operator + to concatenate two strings . I am having an issue with this code that in the operator function we create an instance of the class String , and access it's value directly by using the (.)operator even though the value is a private member of the String Class . But the code gives no such error . I am not able to understand that from which prospect , I am wrong ?

# include<iostream>
# include<cstring>

using namespace std;

class String
{
    char value[80];
public:
    void getData()
    {
        cout << "Enter the string...\n";
        cin.getline(value, 80);
    }
    String operator +(String s2);
    void display()
    {
        cout << value;
    }
};

String String::operator+(String s2)
{
    String s3;
    strcpy(s3.value, value);
    strcat(s3.value, s2.value);
    return s3;
}

int main()
{
    String s1,s2,s3;
    s1.getData();
    s2.getData();
    s3 = s1 + s2;
    s3.display();
}
  • 1
    Does this answer your question? [Why do objects of the same class have access to each other's private data?](https://stackoverflow.com/questions/6921185/why-do-objects-of-the-same-class-have-access-to-each-others-private-data) – MSpiller May 08 '20 at 08:30
  • Thank you so much @M.Spiller – Keerat Sachdeva May 08 '20 at 09:04

0 Answers0