• C

Constructors in C??


I am trying to use constructors in C as in c++. I want the variables of the structure to be initialised at the point of creating an instance. Is it possible in C?

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

constructors are not a feature of C.
the only way you can initialise
at the creation time is doing something like
for example:

typedef struct{
      char *name;
      int roll_number;

int main()
             //some code
           DATA a [] = { "austin", 1,
                                      "bourne", 2'
                                       "smith", 50};              //a will be an array of 50 DATA type structiures, initilised as u can see
No, you need to initialize each time or write a free function and call it every time you allocate the
structure, i.e.

struct Foo {
  int a, b;
  char c;
  long l;

struct Foo initial_foo_value[] =
           15, /* a */
           23, /* b */
           'X'  /* c */

struct Foo* make_foo()
    struct Foo* n = malloc(sizeof(struct Foo));

    *n = *initial_foo_value;
    n->l = n->a + n->b;
About the closest you can come to that is to follow the advise above, and maybe package it as a universal constructor macro, something like:

#define Make(it)  struct it * Make_#it()  \
    struct it * n = malloc(sizeof(struct it));
    if( n != NULL ) * n = initial_#it#_value;
    return n;
Increase Security & Decrease Risk with NSPM Tools

Analyst firm, Enterprise Management Associates (EMA) reveals significant benefits to enterprises when using Network Security Policy Management (NSPM) solutions, while organizations without, experienced issues including non standard security policies and failed cloud migrations

that brings us to the Q of do we need destructors too ,,
obviously since you malloc , you better free it too ..
Like someone said before, constructors are not allowed in plain ANSI C.
However, if you are using a C++ compiler to compile your code (e.g. Microsoft's compiler), then you can add constructors/destructors to your structs provided your source file has a .cpp extension and not a .c extension.

So the following is perfectly valid if you use C++ compiler:

// MyStruct.cpp file

struct MyStruct
int nInt;
double dVal;
char* psChar;


  nInt = 0;
  dVal = 0.0;
  psChar = NULL;


Similarly, you can use functions as members of the structure, you can also use access specifiers like private, public etc.
Please note that unlike classes, public is the default access specifier in a structure.
Hope this helps!
A common tool for C++ folks when forced into ANSI-C land is the undefined structure - you declare the structure to exist (so people can have pointers to it) but you don't declare the actual contents (so nobody else can fiddle with it).

Your public header files goes something like this

#ifndef _MYCLASS_H_
#define _MYCLASS_H_
struct MyClass_s;
typedef struct MyClass_s MyClass;
MyClass *myClass_new( arguments for constructor... );
void myClass_delete( MyClass *instance );
int myClass_exampleMethod( MyClass *instance, arguments.... );

Your C implementation module goes something like this
#include MyClass.h
  int exampleData;
} MyClass;
MyClass *myClass_new( arguments for constructor... )
  MyClass *result = malloc(sizeof(*result));
  if( result )
    /* initialise structure here using arguments */
  return result;
void myClass_delete( MyClass *instance )
  if( instance )
    /* free up any data you allocated earlier, then finally */
    memset(instance,0,sizeof(*instance)); /* optional */
int myClass_exampleMethod( MyClass *instance, arguments.... )
  int result;
  result = arguments plus instance->exampleData;
  return result;

The net effect is that you have a nice private class that only exposes the API it wants to expose to the outside world, and all in C.
The downside is that anything that needs to know what a MyClass structure really looks like needs to be in that file*, and you still don't have any inheritance.
However, you do have TOTAL control over how your structure is created, destroyed and accessed - nobody can create a MyClass object except through your newMyClass method (or any other methods you care to create - an array constructor might be useful).

*Note:  If necessary, you can put the MyClass structure definition into a private header file and just hope nobody else includes it on the sly.  This allows you to split your "class" implementation into multiple .c files.
Other note: The memset just before the free() is optional, but I'd advise you keep it in there unless you've got Purify or some equally effective tool for checking for illegal memory accesses.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.