Search code examples
c++structmemory-managementcoding-styleheap-memory

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!


Solution

  • 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?

    As answered before, you can create a new instance on the heap either via new or with malloc.

    Or, better yet: is it unnecessary for me to cling so tightly to the notion that I shouldn't define member functions for structs?

    This is the more interesting question. The major (only?) difference between struct and class in c++ is the default access specifier. That is, struct defaults to public access and class defaults to private. In my opinion, this is the difference that should determine which of the two you use. Basically, if users should access the members directly, then it should be a struct.

    If, for example, you have no member functions, then obviously the intention is for the object's members to be accessed directly and so it would be a struct. In the case of an object that is just a small private helper for the implementation of its outer class, as in your example, then even if it has member functions it is often clearest to allow the outer class access to its members and so it should be a struct. Often with these classes the implementation of the outer class is tightly coupled to the implementation of the inner class and so there is no reason to hide the one from the other.

    So, for trivial (e.g. std::pair) objects or those whose use is limited (as in a private inner class) default access to members can be a good thing, and in these cases I would make them structs.