Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


2 Answers

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.

like image 88
Jon Avatar answered Dec 22 '25 18:12

Jon


In that scope, there is nothing called myIng. The error is pretty clear on that. Its Ingredient& target who has a myIng member, so you should write:

target.myIng = MyString("hello");
like image 26
K-ballo Avatar answered Dec 22 '25 18:12

K-ballo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!