I implemented edges (as in graphs) using 4 classes: Node, Node_Linkedlist, Edge, Edge_Linkedlist.
Node has a private int member and Edge has 2 reference members to Node:
private:
Node& in;
Node& out;
Edge has 2 working constructors such that Edge supports both Node and const Node.
Edge(Node& tmpin, Node& tmpout) : in(tmpin),out(tmpout) {};
Edge(const Node& tmpin, const Node& tmpout) : in(Node(tmpin)),out(Node((tmpout))) {};
The << operator:
ostream& operator<<(ostream& out, const Edge& node)
{
out<<node.in<<endl;
return out;
}
This works for Node but not for const Node. In const Node, as the debugger into the scope of the operator it dumps the int values of Node. Why doesn’t the operator work for const Node?
Your code is invalid – you’re binding a non-const reference to a temporary in the constructor –
Node(tmpin)andNode(tmpout)are temporaries – and running into undefined behavior. To supportconst, you either need to make your membersconst, pointers or make them objects instead of references.Personally, I would make them smart pointers: