Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor for structs in C

Given:

struct objStruct {     int id;     int value; };  typedef struct objStruct Object; 

Is there a shortcut to allocate and initialize the object, something like a C++ constructor?
It could even be a preprocessor macro. Whatever makes the code shorter and more readable than this:

Object *newObj = malloc(sizeof(Object)); // successful allocation test snipped newObj->id = id++; newObj->value = myValue; 
like image 912
Aillyn Avatar asked Sep 22 '10 22:09

Aillyn


People also ask

Can we have constructor for struct in C?

3. Constructor creation in structure: Structures in C cannot have a constructor inside a structure but Structures in C++ can have Constructor creation.

Can you make a constructor for a struct?

A structure called Struct allows us to create a group of variables consisting of mixed data types into a single unit. In the same way, a constructor is a special method, which is automatically called when an object is declared for the class, in an object-oriented programming language.

Do you need constructor for structs?

Technically, a struct is like a class , so technically a struct would naturally benefit from having constructors and methods, like a class does. But this is only “technically” speaking.

How many constructor can a struct have?

A structure type definition can include more than one constructor, as long as no two constructors have the same number and types of parameters.


1 Answers

In C I typically create a function in the style of a constructor which does this. For example (error checking omitted for brevity)

Object* Object_new(int id, int value) {    Object* p = malloc(sizeof(Object));   p->id = id;   p->value = value;   return p; }  ... Object* p1 = Object_new(id++, myValue); 
like image 190
JaredPar Avatar answered Oct 14 '22 06:10

JaredPar