Question

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).

Was it helpful?

Solution

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.

OTHER TIPS

When the "custom creator" method (correctly termed the "constructor") for the Node class runs, any members of Node which are themselves objects (i.e. not basic types like ints, floats, chars, and not pointers) will have their own constructors run.

So the initial value of the edge object will be determined by what the constructor of the Edge class does. If the Edge class constructor requires arguments, then the Node constructor will have to provide them.

Suppose, for example, that the Edge constructor requires an integer called weight, e.g.:

class Edge {
  public:
    Edge(int w)
      : weight(w) {
    }

  private:
    int weight;
};

Then there are two options for giving a default weight to this edge. You can give the edge constructor have a default value for this parameter:

class Edge {
  public:
    Edge(int w = 0)
      : weight(w) {
    }

  private:
    int weight;
};

In which case the Node class does not need to do anything special. Or, you can have the Node class provide the parameter, e.g.:

class Node {
  public:
    Node()
      : edge(0),
        parent(NULL) {
    }

    Data data;
    Edge edge;
    Node *parent;
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top