ma************@gmail.com wrote:
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.
--
Eric Sosman
es*****@acm-dot-org.invalid