constructor?

G

Gernot Frisch

Hi,

since C does not support construcor functions for structs, what is the
usual approach to write this C++ code in C:
Code:
struct foo
{
    foo() {bar=0;}
    int bar;
};

int main()
{
    foo f[5];
}

I would write:
Code:
struct foo
{
    bar;
};

Init(foo& f)
{
    bar=0;
}

int main(int, char**)
{
    foo f[5];
    // Put this in a Macro: INIT(f)?
    for(int i=0; i<sizeof(f)/sizeof(f[0]); ++i)
       Init(f[i]);
return 0;
}

Any better ideas?
 
N

Nelu

Gernot Frisch said:
Hi,

since C does not support construcor functions for structs, what is the
usual approach to write this C++ code in C:
Code:
struct foo
{
foo() {bar=0;}
int bar;
};

int main()
{
foo f[5];
}

In C, you usually write initialization function to do the job of C++ constructors.
I would write:
Code:
struct foo
{
bar;
};

Init(foo& f)
{
bar=0;
}
[/QUOTE]

There's no passing by reference in C. You'll have to pass a pointer (by-value):

Init(foo *f) {
  f->bar=0;
}

f->bar instead of bar, because you don't know where bar belongs.
 [QUOTE]
int main(int, char**)
{
foo f[5];
// Put this in a Macro: INIT(f)?
for(int i=0; i<sizeof(f)/sizeof(f[0]); ++i)
Init(f[i]);
return 0;
}[/QUOTE]

Call the function I wrote above like this:
 Init(&f[i]); 
instead of
Init(f[i]);
(the reference thing that does not exist in C)
[QUOTE]
Any better ideas?[/QUOTE]

It may be good to rename Init to foo_init. Keeps name clashing at bay :-)
 
M

Mark McIntyre

Hi,

since C does not support construcor functions for structs, what is the
usual approach to write this C++ code in C:

struct foo { int bar; };

int main(void)
{
struct foo f[5] = {0};
return 0;
}

This works because if you initialise the first element of an array,
the remainder is set to zero by default.
Any better ideas?

If you want to do something more complex than initialising the first
element, then you need to switch mindset to C and avoid using C++
models. The languages are different and its not often a good idea to
try to foce one language to emulate another.
--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
 

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
474,265
Messages
2,571,069
Members
48,771
Latest member
ElysaD

Latest Threads

Top