Search code examples
c++friend

Why I can't use the `private` field in the `friend` operator?


Header file has it:

class Shape_definition {
private:
    // ...
    std::vector<Instruction> items;         
public:
    //...
    friend std::istream& operator >> (std::istream& is, Shape_definition& def); // FRIEND!
};
//-----------------------------------------------------------------------------
std::istream& operator >> (std::istream& is, Shape_definition& def);
//...

Definition code:

std::istream& operator >> (std::istream& is, Bushman::shp::Shape_definition& def){
    //...
    Bushman::shp::Instruction instr = Bushman::shp::Instruction::get_empty();
    while(is >> instr) def.items.push_back(instr); // Problem is here!
    return is;
}

But I get an error in the MS Visual Studio editir:

error C2248: 'Bushman::shp::Shape_definition::items' : cannot access private member declared in class 'Bushman::shp::Shape_definition'

Why I can't use the private field in the friend operator?

Thank you.


Solution

  • After some detective work, I'll assume Shape_definition is defined inside a namespace, and so is your declaration of std::istream& operator >> (std::istream& is, Shape_definition& def);.

    You then define another std::istream& operator >> (std::istream& is, Bushman::shp::Shape_definition& def) outside the namespace. Since this isn't your friend, access is blocked.

    Try defining it as:

    namespace Bushman
    {
      namespace shp
      {
        std::istream& operator >> (std::istream& is, Bushman::shp::Shape_definition& def){
            //...
            Bushman::shp::Instruction instr = Bushman::shp::Instruction::get_empty();
            while(is >> instr) def.items.push_back(instr); // Problem is here!
            return is;
        }
      }
    }