-2

I am trying to overload the operator<< from the class second. The problem is some of the data I am trying to access is private in class first. Why am I unable to access the private data since I am using the friend function?

I found that the overload is only working with non-inherited private data.

class first
{
public:

    student(string a, string b, float c, int d);

private:
    string a;
    string b;
    float c;
    int d;
    int e;
    static int count;   
};


class second : public first
{
public:

    second(string a, string b, float c, int d, string f);


    friend ostream &operator << (ostream &output, second &dS);
    friend istream &operator >> (istream &input, second &dS);

private:
    string f; 
};


// Separate File

ostream &operator <<(ostream& output, second& dS){

    output << iS.a << endl;

    output << iS.f << endl;


return output;
}

This is the error I am getting:

overload.cpp:27:18: error: 'a' is a private member of 'first'
    output << dS.a << endl;
                 ^
./example.hpp:51:9: note: declared private here
        string a; 
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
drowsell
  • 21
  • 5
  • 1
    its because second doesnt have access to those variables. They have to be protected instead of private if you want to have access to them in child class – Matriac Oct 09 '19 at 21:31
  • 1
    `class second` **also** cannot access those variables. That is how `private` works. They are privately owned by`class first`. – Drew Dormann Oct 09 '19 at 21:35
  • 4
    Your friends can see your private parts, but they can't see your parents' private parts. – Fred Larson Oct 09 '19 at 21:38

2 Answers2

1

When you write

friend ostream &operator << (ostream &output, second &dS);

you are allowing some external function with that signature to have access to any internal attribute/member your second class has access. That means operator<< will have access to the attribute f even though it is private. However, your second class does not have access to the private data from the base class. Thus, it cannot give that access to a friend function.

darcamo
  • 3,294
  • 1
  • 16
  • 27
0

As the others said, the second Class does not have access to the private members of the first class. You could try writing some set and get methods in the first class. The get methods would return the value (that i'm assume you're seeking). You could call this function in the second class. Not sure if that's going overboard for what you're looking for though. Might just want to do the overloading in the fist class

Brian
  • 23
  • 1
  • 4