Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create a new struct on the heap without defining a constructor?

I understand that there are very few differences between structs and classes in c++ (two?). Be that as it may, I've been instructed to use structs to define simple little things like nodes that might not need member functions (despite the fact that I could technically include include member functions). For instance I might define a node as a private member of a linked list class as follows:

class LinkedList {
  struct Node {
    MyObject *data;
    Node *next;
  };

  Node *list;

};

In this case, however, is it possible to create a new instance of this struct on the heap, or would I need to define a constructor? Is there a way to create things on the heap without the new operator? Or, better yet: is it unnecessary for me to cling so tightly to the notion that I shouldn't define member functions for structs? Should I just go ahead and define one? Or if I did that, would it be like admitting that Node really aught to be an inner class, rather than an inner struct? Should I really be worrying about these sorts of things at all? Which is more readable?

Thanks!

like image 365
Ziggy Avatar asked Dec 13 '10 04:12

Ziggy


1 Answers

Even if you don't define a constructor, the compiler will create a default one and so you can use operator 'new':

Node *n = new Node;

AFAIAC, a struct is a class, except that its "publicness" default is reversed.

like image 183
Android Eve Avatar answered Sep 28 '22 03:09

Android Eve