Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Constructors in C??

Posted on 2004-11-14
6
Medium Priority
?
313 Views
Last Modified: 2010-04-15
Hi,

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?

0
Comment
Question by:ksanand_be
6 Comments
 
LVL 5

Assisted Solution

by:van_dy
van_dy earned 200 total points
ID: 12579954
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
0
 
LVL 23

Assisted Solution

by:Mysidia
Mysidia earned 200 total points
ID: 12579955
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;
}
0
 
LVL 22

Assisted Solution

by:grg99
grg99 earned 200 total points
ID: 12580185
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;
}
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 11

Expert Comment

by:avizit
ID: 12581493
that brings us to the Q of do we need destructors too ,,
obviously since you malloc , you better free it too ..
0
 

Assisted Solution

by:AniOnLine
AniOnLine earned 200 total points
ID: 12582639
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;

MyStruct();
~MyStruct();
};

MyStruct::MyStruct()
{
  nInt = 0;
  dVal = 0.0;
  psChar = NULL;
}

MyStruct::~MyStruct()
{
   if(psChar)
   {
       free(psChar);
   }
}

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

Accepted Solution

by:
Peter-Darton earned 600 total points
ID: 12593306
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.... );
#endif

Your C implementation module goes something like this
#include MyClass.h
struct
{
  int exampleData;
} MyClass;
MyClass *myClass_new( arguments for constructor... )
{
  MyClass *result = malloc(sizeof(*result));
  if( result )
  {
    memset(result,0,sizeof(*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 */
    free(instance);
  }
}
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.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
Suggested Courses

580 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