many times it comes natural that instances of two or more classes, most likely ones that share a header file, will refer to one another by pointers. for example, in a graph, an edge needs to refer to its vertices and vice versa. the mutual reference alone can be done by forward declaration, but i wish that both classes could opperate on one another, i.e use each other's methods or fields. for example, i'd like that when connecting an edge to a vertex, both pointers (edge->myVertex, vertex->myEdge) could be assigned in a single method, which can be of either one of the classes. is there a way to do it? thanks.
Asked
Active
Viewed 584 times
0
-
the only way for "i'd like that when connecting an edge to a vertex, both pointers (edge->myVertex, vertex->myEdge) could be assigned in a single method, which can be of either one of the classes. is there a way to do it?" to occur is mutual friend from both classes. i.e. A friends B, and B friends A. – Nathan Ernst Mar 31 '13 at 07:29
2 Answers
1
The way to do it is to use free-functions, i.e., algorithms to do those things. Otherwise, your classes lose their semantics. For example, you can have:
void connect_vertices(Vertex<T> v1, Vertex<T> v2, Edge<T> e) {
}
function handling that logic.

perreal
- 94,503
- 21
- 155
- 181
-
I know this option, but thanks anyway.. one other thing - is there a good reason for the lack of ability to do that with methods? for all I know, the compiler is already going over the code twice.. why can't it be aware of the class below? could it create some problem if it had allowed it? thanks again.. – elad Mar 31 '13 at 00:28
0
Is this what you're thinking of?
void Edge::setVertex(Vertex &v)
{
myVertex = &v;
v.myEdge = this;
}

Beta
- 96,650
- 16
- 149
- 150
-
exactly. now that you put it this way, I have to confess that I almost always implement the class as a whole in the header file. could it be that outside the header, like you wrote it, it will work just fine? if so, will it still have other limitations connected to mutual reference? – elad Mar 31 '13 at 00:51
-
1@elad: Yes, it'll work. You'll have to do the forward declaration right, but you'd have to do that anyway. The only cost I can see is that this method must have access to `Vertex::myEdge`. To make the variable `public` is terrifying, to make `Edge` a `friend` is overkill, and to make *this method* a `friend` is something I'd have to look up. (I don't like `friendship` in general.) – Beta Mar 31 '13 at 01:03
-
thank you very much. I also don't like `friendship` but only in that sense ;-) I'll try that and come back here if something goes wrong, or if i find anything interesting.. – elad Mar 31 '13 at 06:26