1

I am learing C++ while I see some codes the structs are initialized in diffent ways, For example

 typedef struct Node {
        Node *p; 
        Node *n; 
        int data; 
    }Node;

What is the difference between these two ways, or both are same,

Node* root = new Node();

vs

Node* root = new Node;

Thanks in advance !!

Wickkiey
  • 4,446
  • 2
  • 39
  • 46
  • 2
    In C++, don't use `typedef` and skip the `Node` after the closing brace. – Frank Puffer May 01 '16 at 17:01
  • @FrankPuffer May I know the reason for the suggested syntax .. – Wickkiey May 01 '16 at 17:04
  • 2
    You are using C syntax. In C++ a `struct` is the same as a `class` except that all elements are public by default. Therefore you should declare a `struct` in the same way as a `class`. – Frank Puffer May 01 '16 at 17:07
  • @VivekAnanthan: Why don't *you* explain why you chose this obscure, obfuscating syntax? In which C++ training did you learn that? – Kerrek SB May 01 '16 at 17:25
  • @KerrekSB I am surfing through net and learing .. I seems I m not going in a good way .. Can you please suggest some good materials – Wickkiey May 01 '16 at 17:29
  • Have a look at the [recommended books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) maybe. – Kerrek SB May 01 '16 at 19:19

1 Answers1

1

There's absolutely no difference, whatsoever.

Furthermore, in modern C++ there's also a third option too, and this is now the preferred syntax:

Node* root = new Node{};

In this case, all three alternative syntaxes are valid. As you proceed and learn more C++, you will find out in which situations some of these alternatives syntaxes can and cannot be used.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148