Nosrettap
Nosrettap

Reputation: 11340

How to create a struct in C++

Suppose I have a struct called Node as follows:

struct foo
{
   foo *next;
   int aNum;
};

How do I create an "instance" of this in C++ (in a main method for instance)? I've looked around and it seems as if I would just do

foo name;

But it seems to me as if I should have to allocate space first. Can someone explain (a long explanation is not necessary)

Upvotes: 1

Views: 4772

Answers (2)

user142019
user142019

Reputation:

foo name; is the way to do it. This will allocate storage for it on the stack, which is called static allocation (except when the variable is global, which means it will be allocated in the program executable file itself).

If you want to allocate it dynamically (you often don't need to do that in C++), use std::unique_ptr<foo> name = new foo; or std::shared_ptr<foo> name = new foo;. Also see std::unique_ptr reference and std::shared_ptr reference.

Upvotes: 3

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76876

If you define your instance like this, it is an object of automatic storage duration. That means that the compiler generates code for you that takes care of allocating and freeing the memory for that object.

This method has limitations. The lifetime of an object created in this way is always bound to the lifetime of a surrounding function or an owning object. Also, if the object is a local variable inside a function, it will usually be allocated on the stack, which is usually quite limited in size.

Upvotes: 2

Related Questions