Search code examples
c++friend-function

c++ error : (private data member) was not declared in this scope


Say I have a class like so:

class Ingredient
{
    public:
        friend istream& operator>>(istream& in, Ingredient& target);
        friend ostream& operator<<(ostream& out, Ingredient& data);
    private:
        Measure myMeas;
        MyString myIng;
};

In this overloaded friend function, I'm trying to set the value of myIng

istream& operator>>(istream& in, Ingredient& target)
{
    myIng = MyString("hello");
}

In my mind, this should work because I'm setting the value of a private data member of the class Ingredient in a friend function and the friend function should have access to all the private data members right?

But I get this error: ‘myIng’ was not declared in this scope Any idea on why this is happening?


Solution

  • Because you need to be be explicit that you are accessing a member of the target parameter, not a local or global variable:

    istream& operator>>(istream& in, Ingredient& target)
    {
        target.myIng = MyString("hello"); // accessing a member of target!
        return in; // to allow chaining
    }
    

    The above will work exactly because the operator is a friend of Ingredient as you mention. Try removing the friendship and you will see that accessing private members will no longer be possible.

    Also, as Joe comments: stream operators should return their stream parameter so that you can chain them.