0

I realize this is a very basic question but I'd like to see an example of when I should be setting some of my class member variables as pointers.

I saw this class definition:

template<class T>
class Node
{
public:
    T data;
    Node<T> * next;
    Node<T>(const T& d):data(d), next() {}
    Node<T>(const Node<T>& copyNode) : data(copyNode.data), next() {}

private:
    Node<T>& operator=(const Node<T>&);
};

And I'm not sure why next should be a pointer member variable?

user2121792
  • 221
  • 1
  • 5
  • 12
  • possible duplicate of [Why should I use a pointer rather than the object itself?](http://stackoverflow.com/questions/22146094/why-should-i-use-a-pointer-rather-than-the-object-itself) – user657267 Jun 18 '15 at 05:37

2 Answers2

2

For arguments sake, lets assume you didn't declare next to be a pointer, but a value instead:

Node<T> next;

Then when you assign to next you create a new copy of the original object, leading you to have two unrelated and unconnected copies.

A pointer is exactly what it sounds like, it's pointing to some other object. It's like saying "the next object is the one over there".

Pointers are essential for anything that needs to be dynamic, like a linked list.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 2
    Also hard to get Node to contain Node since Node is not yet fully defined. Probably a good thing. Node containing Node would lead to a demented RAM-consuming recursion. – user4581301 Jun 18 '15 at 05:45
0

Class node represents a linked list then for pointing to the next node of linked list you will require a variable but you want your list to grow dynamically and so you can create a new node at any time and link it to the rest of linked list via the next pointer in which you store the address of the newly created node.
Also if next is not a pointer then sizeof Node would not be able to calculate its size as the data member is of same type so it will again try to calculate the size and so it is a compiler error.In case of pointer, all pointer variables are of 4 byte so no issue there.