Constructor Destructor in Structure

Apr 12, 2011 at 12:14am
Is it possible to have a structure say initialise itself without defining it as a class? I'm probably being pedantic, so let me know if I am.

e.g.

1
2
3
4
typedef struct a
{
   char *ch;
} a_t;


Something that would initialise ch to null.
Apr 12, 2011 at 3:27am
closed account (D80DSL3A)
A structure can have a constructor, just like a class.
Why typedef?
1
2
3
4
5
struct a
{
   char *ch;
   a(): ch(NULL){}// constructor initializes ch = NULL
} a_t;
Apr 13, 2011 at 12:22am
Thankyou, that will be handy to know.
'typedef' so that a_t becomes a variable type.
Apr 13, 2011 at 1:41am
closed account (D80DSL3A)
You're welcome. I'm still confused about using typedef for a structure. The structure a IS it's own variable type:
a a1, a2, a3;// 3 instances of the variable type a are declared here
Could you show an example where the typedef is helpful?
Apr 13, 2011 at 2:58am
closed account (1yR4jE8b)
1
2
3
4
typedef struct a
{
   char *ch;
} a_t;

This is standard C.


1
2
3
4
5
struct a
{
   char *ch;
   a(): ch(NULL){}// constructor initializes ch = NULL
} a_t;

This is the C++ way of doing it, both ways are valid in C++ because compilers need to be backward compatible with C. However typically, you ignore the second typename at the end of the C++ style struct definition...

1
2
3
4
5
struct a
{
   char *ch;
   a(): ch(NULL){}// constructor initializes ch = NULL
};


Semantically, there is no difference.
Apr 13, 2011 at 2:58am
closed account (1yR4jE8b)
EDIT: removed a double post

wtf, there's like 3 copies of this thread?
Last edited on Apr 13, 2011 at 2:59am
Apr 13, 2011 at 3:09am
closed account (D80DSL3A)
@darkestfright. Thanks for the explanation.
This is standard C.
That explains why I didn't recognize it.
Apr 13, 2011 at 3:19am
Thanks also, there's a lot of C++ syntax I'm not familiar with.
Apr 13, 2011 at 3:23am
All you need to know is C++ is created to be backward-compatible to old existing C code and with such baggage you can have such "cross-breed" code.

All new C++ programs should strive to do it the "C++ syntax way" and for legacy C program maintenance, we revert back to "C syntax way".

I don't really recommend "cross-breed" code but that is entirely my personal opinion of cuz.
Topic archived. No new replies allowed.