I was recently reading about ways to create something that resembles c++ objects, but in C, and I came across some pretty good examples. However, there was this single piece of code that had me thinking for hours, since it was the first time I saw this kind of syntax, and I didn't find anything like it on Google...
The block itself is this one:
struct stack {
struct stack_type * my_type;
// Put the stuff that you put after private: here
};
struct stack_type {
void (* construct)(struct stack * this); // This takes uninitialized memory
struct stack * (* operator_new)(); // This allocates a new struct, passes it to construct, and then returns it
void (*push)(struct stack * this, thing * t); // Pushing t onto this stack
thing * (*pop)(struct stack * this); // Pops the top thing off the stack and returns it
int this_is_here_as_an_example_only;
}Stack = {
.construct = stack_construct,
.operator_new = stack_operator_new,
.push = stack_push,
.pop = stack_pop
};
Assuming all the functions being set to the pointers are defined somewhere else, my doubts are the following:
1) Why does the point ( '.' ) mean, or whats its purpose when initializing the function pointers? (example: .construct = stack_construct )
2) why is there an equal sign after 'Stack' at the end of the struct definition, and why is there something other than a ';' ( in this case the word 'Stack' ), given the fact that there is no typedef at the beginning? I assume it has something to do with initialization (like a constructor, I don't know), but it is the first time I see a struct = {...,...,...} in the definition. I've seen that when you initialize a struct like in the following example:
typedef struct s{
int a;
char b;
}struc;
void main(){
struc my_struct={12,'z'};
}
But this is not in the main declaration of the struct, and still, there are no '=' within the {}, unlike the first example, where it showed something like...
struc my_struct={ a = 12,
b = 'z'};
3) This is a minor doubt, meaning, I'm much more interested in the first two. Anyway, here it goes... At the beginning of the first code, it says something like '// Put the stuff that you put after private: here'. Why is that? how would that make them private?