Reputation: 908
I have a C code I need to understand. There is a
typedef struct someStruct {
int i;
char c;
someStruct() {
i = 0;
c = 'c';
}
someStruct(char inpChar) {
i = 1;
c = inpChar;
}
} t_someStruct;
(The code doesn't really make sense or serve a purpose, I know. I just simplified it.) So there is this structure and it has two members (int i and char c). The interesting part is that it has basically two constructors, which is a new concept to me. It works normally, but can we write constructors for structures? I couldn't find anything on Google, maybe I am not searching right.
Upvotes: 1
Views: 272
Reputation: 1
Your code is not valid C code (i.e. valid C11) code but it is valid C++ (i.e. C++14) code.
In C++, a struct
is like a class
except that all members are by default public
; see e.g. here.
Upvotes: 7
Reputation: 479
The main difference between C and C++ is that C++ supports class but C does not. In C++ struct is a special class so the above code will work in C++ but not in C.
Upvotes: 0
Reputation: 10385
This code is most probably in C++.
In C++, a struct
is actually similar to a class
, hence you can define constructors for structs in C++.
Try to compile your code in gcc. You'll get a
error: expected specifier-qualifier-list before ‘someStruct’
Upvotes: 3