Default constructor in C

后端 未结 13 655
孤街浪徒
孤街浪徒 2020-12-07 21:02

Is there a way to have some kind of default constructor (like a C++ one) for C user types defined with a structure?

I already have a macro which works like a fast in

相关标签:
13条回答
  • 2020-12-07 21:51

    Following is a simple program that makes use of a constructor. Function "default_constructor" gets called inside main without any explicit function call.

    #include        <stdio.h> 
    
    void __attribute__ ((constructor)) default_constructor() 
    { 
        printf("%s\n", __FUNCTION__); 
    } 
    
    int main() 
    { 
        printf("%s\n",__FUNCTION__);
        return 0; 
    }
    

    Output: default_constructor main

    Within the constructor function you can include some initialization statements and use the destructor function to free memory as follows,

    #include    <stdio.h> 
    #include    <stdlib.h>
    
    struct somestruct
    {
        int     empid;
        char *  name;
    };
    
    struct somestruct * str1;
    
    void __attribute__ ((constructor)) a_constructor() 
    { 
        str1 = (struct somestruct *) malloc (sizeof(struct somestruct));
        str1 -> empid = 30228;
        str1 -> name = "Nandan";
    } 
    
    void __attribute__ ((destructor)) a_destructor()
    {
        free(str1);
    }
    
    int main() 
    { 
        printf("ID = %d\nName = %s\n", str1 -> empid, str1 -> name);
        return 0;
    }
    

    Hope this will help you.

    0 讨论(0)
提交回复
热议问题