Constructors in C??

Posted on 2004-11-14
Last Modified: 2010-04-15

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?

Question by:ksanand_be
    LVL 5

    Assisted Solution

    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;
    } DATA;

    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
    LVL 23

    Assisted Solution

    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;
    LVL 22

    Assisted Solution

    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;
    LVL 11

    Expert Comment

    that brings us to the Q of do we need destructors too ,,
    obviously since you malloc , you better free it too ..

    Assisted Solution

    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!
    LVL 2

    Accepted Solution

    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.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
    Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
    The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
    The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    9 Experts available now in Live!

    Get 1:1 Help Now