c++operator-overloadingfriend-class

C++: grant access to private operator "passing through" a friend class, possible?


Let's say I have defined these two classes:

class Node
{
    friend class list;

public:
    Node (const int = 0);
    Node (const Node &);

private:
    int val;
    Node * next;
    Node & operator=  (const Node &);
};


class list
{
public:
    list ();                                
    list (const list &);                    
    ~list ();                              

    list & operator+= (const Node &);
    Node & operator[] (const int) const;    

private:
    list & delete_Node (const int);
    Node * first;
    int length;
};

and then, within a main.cpp file, I have these lines:

list l1;

l1 += 1;
l1 += 41;
l1[1] = 999;    // <-- not permitted: Node::operator= is private

My question is: is it possible to grant access to Node::operator= if and only if the lvalue is a reference within a list (which is a friend class of Node) even if main() is not a friend function?


Solution

  • That won't work, but this will:

    class Node
    {
        friend class list;
    
    public:
        Node (const int = 0);
        Node (const Node &);
    
    private:
        int val;
        Node * next;
        Node & operator=  (const Node &);
    };
    
    class Magic
    {
    public:
        operator Node&() { return node; }
        Node& operator=(int v) { return list::assign(node, v); }
    
    private:
        friend class list;
        Magic(Node& n) : node(n) {}
        Node& node;
    };
    
    class list
    {
    public:
        Magic operator[] (int) const { return const_cast<Node&>(*first); }
    
    private:
        static Node& assign(Node& n, int v) { n.val = v; return n; }
    };
    

    Now forget you ever saw this, because's probably a very bad design anyway.