Question about struct aspect of standard

E

Eric Sosman

Can standard C structs have a constructor? Thanks in advance.

C has no constructors, and no destructors either.
You can initialize a struct at the point of declaration

struct mystruct s = { 1, 42.0, "blue" };

.... or you can assign to it from another pre-initialized
struct:

const struct mystruct proto_s = { 0, 0.0, "" };
...
struct mystruct s;
...
s = proto_s;

.... or you can (manually) initialize its elements by
calling a function:

void init_mystruct(struct mystruct *);
...
struct mystruct s;
init_mystruct(&s);

.... or you can write a function that serves as a "factory
method," allocating and initializing a struct:

struct mystruct *factory( ...args... );
...
struct mystruct *sp, s;
sp = factory( ...args... );
if (sp == NULL) die();
s = *sp;

.... and there are lots more variations. However, nothing
in C will cause any of this to happen automagically; you'll
need to perform the machinations yourself.
 
P

pemo

Can standard C structs have a constructor? Thanks in advance.

The answer is 'no', but it could be a 'may be' depending upon what it is
you're trying to achieve. If it's a C++ clone, then, *not very easily* ...
even given the ol' cfront mechanisms.

So, what do you mean - *exactly*?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,040
Latest member
papereejit

Latest Threads

Top