I'm having trouble understanding some C++ concepts.
When is it appropriate to use a member pointer vs a member variable?
Let's say I have a tree structure and thus a Node
class. My intuition would be to use a variable for its Data
and Edge
(because the Node
"owns" the Data
) and a pointer to the parent Node
. Is this correct?
class Node {
public:
Data data;
Edge edge;
Node *parent;
}
When I implement a custom creator method for the Node
class, I also have to initialize the member variables (but not the pointers?). For the root Node
I can set the parent pointer to NULL
.
But what do I do with the Edge
variable? The root Node
has no parent and no Edge
leading to it from its parent. Can I somehow set it to a "zero" value? If it matters, the Edge
class has no default constructor, but something like this: Edge(int length, int width)
.
For appropriate use of member pointer vs. member variable, see this discussion.
Now, here is what you can do with the Edge
class with regard to the "zero" value:
Change the constructor of Edge
to read:
Edge(int length=0, int width=0)
This way when Edge
is default constructed with Edge e1
(or implicitly with Node n1
), that constructor will be matched and the default values as specified will be used.
I'd say an edge of length 0 and width 0 makes perfect sense as a "zero" edge.
I've only listed one way to define default values for the constructor. There is additional discussion on the topic here.