Aurélie JEAN
Aurélie JEAN

Reputation: 195

value by default for a pointer in a structure in C++

I have a struct named Node which has 2 attributes: an int v and another Node* named child. If I do not explicitly provide a constructor for my struct, what value does child receive by default?

struct Node   
{
    int v;
    Node * child; 
};

It seems that it is not the NULL pointer, so I had to write a constructor inside my structure

struct Node   
{
    int v;
    Node * child; 
    // constructor
    Node():v(0),child(NULL){}
};

Upvotes: 3

Views: 1841

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320391

The initial value of child pointer in this case will depend on external factors determined at the point of object definition: storage duration of Node object and initializer (if any).

  • If you declare a Node object with static storage duration, the pointer will be zero-initialized.

    Node n1; // `n1.child` is null pointer
    
    void foo()
    {
      static Node n2; // `n2.child` is null pointer
    }
    
  • If you declare a Node object with automatic storage duration and an initializer, the pointer will initialized as directed by the initializer

    void foo()
    {
      Node n3{}; // `n3.child` is null pointer
      Node n4 = { 42 }; // `n4.child` is null pointer
    }
    
  • If you declare a Node object with automatic storage duration and no initializer, the pointer will not be initialized at all

    void foo()
    {
      Node n5; // `n5.child` is garbage value
    }
    
  • If you allocate a Node object dynamically with an initializer, the pointer will initialized as directed by the initializer

    Node *n6 = new Node(); // `n6->child` is null pointer
    Node *n7 = new Node{}; // `n7->child` is null pointer
    Node *n8 = new Node{ 42 }; // `n8->child` is null pointer
    
  • If you allocate a Node object dynamically without an initializer, the pointer will not be initialized at all

    Node *n9 = new Node;   // `n9->child` is garbage value
    
  • If you declare Node as a subobject of a bigger object, the initialization rules propagate from bigger object to Node subobject.

If you want your class members to be zero-initialized in all cases, you can explicitly write a constructor or use C++11 member initializer syntax

struct Node   
{
    int v = 0;
    Node *child = nullptr; 
};

Upvotes: 0

Jon Purdy
Jon Purdy

Reputation: 54971

It will be uninitialised. Reading from it before setting its value in the constructor initialiser list, or the constructor body, is undefined behaviour.

Note that there are two exceptions: variables with static storage duration, and objects created with new Node() (as opposed to new Node). In both those cases, the object will be zero-initialised.

Upvotes: 4

Related Questions