Search code examples
c++private

Private element error


Class 1:

class Class1{
public:
    Class1(Class2 * a, int b );
    ~Class1();
    friend ostream& operator<< (ostream& x, const Class1& c1);

private:
    int b;
    Class2 * a;
};

ostream& operator<< (ostream& x, const Class1& c1)
{
    stream<<"("<<c1.a->label<<","<<c1.b<<")"<<endl;
    return x;
}

Class2 (In another file):

class Class2
{
public : 
   Class2 (string label);
   ~Class2();
  string getLabel()
  {
     return label; 
  }

private:
    string label;
    vector<Class1 *> c1vector;
};

Question:

I'm trying to print the label and b of an edge, but it says the label is private. Can you tell me what I'm doing wrong? Thanks.


Solution

  • Well, you are trying to access a private member of Class2 directly, and the private property is actually what prevents you from doing this. (And the fact that you qualified operator<< friend in Class1 doesn't change anything, label is a private member of Class2).

    Either make the member public (not recommended) or provide a public member function that returns the value of this member.