3

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?

grd
  • 287
  • 1
  • 2
  • 8

1 Answers1

2

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.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 2
    I think you could nest `Magic` inside `list` and remove the need for `assign` and the namespace pollution completely, something like [this](http://coliru.stacked-crooked.com/a/cebef3b8d146665b). – TartanLlama Nov 01 '16 at 11:39
  • 2
    @TartanLlama: Yes indeed when this kind of thing is done for real the "Magic" proxy class is usually put inside the list class. But it's only a slight decrease in horror. :) – John Zwinck Nov 01 '16 at 11:44