Overflowh
Overflowh

Reputation: 1104

Pointer to a C++ structure

If I create a structure in C++ like this:

typedef struct node {
    int item;
    int occurrency;
};

I know that a structure is allocated in memory using successive spaces, but what is the name of the structure (node in this example)? A simple way to give a name to the structure?

Upvotes: 0

Views: 2035

Answers (3)

Jesse Good
Jesse Good

Reputation: 52355

In C

struct node {
    int item;
    int occurrency;
};

is a tag, and by itself, it doesn't represent a type. That is why you cannot do

node n;

You have to do

struct node n;

So, to give it a "type name", many C programmers use a typedef

typedef struct node {
    int item;
    int occurrency;
} node;

That way you can do

node n;

Instead of

struct node n;

Also, you can omit the tag and do the following

typedef struct {
    int item;
    int occurrency;
} node;

However, in C++ this all changes, the typedef syntax is no longer needed. In C++ classes and structs are considered to be user-defined types by default, so you can just use the following

struct node {
    int item;
    int occurrency;
};

And declare nodes like this

node n;

Upvotes: 3

MSalters
MSalters

Reputation: 179779

node is the name of the type. You can have multiple objects of that type:

struct node {
  int item;
  int occurrency;
};
node a;
node b;

In this example, both a and b have the same type (==node), which means that they have the same layout in memory. There's both an a.item and a b.item.

Upvotes: 2

Constantinius
Constantinius

Reputation: 35039

In C++ you don't have to use typedef to name a structure type:

struct node {
    int item;
    int occurrency;
};

is enough.

A pointer to an instance of that struct would be defined as node* mypointer;

E.g: You want to allocate a new instance with new:

node* mypointer = new node;

Upvotes: 3

Related Questions