1

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.

Jan Spurny
  • 5,219
  • 1
  • 33
  • 47
lulijeta
  • 900
  • 1
  • 9
  • 19
  • 14
    It's most likely C++ code, not C code. – Paul R Mar 18 '15 at 13:22
  • in C++, a struct is a type of Class and that code will work but not in C. If you want something similar in C - see https://stackoverflow.com/questions/17052443/c-function-inside-struct – Simon Peverett Mar 18 '15 at 13:26
  • If it doesn't compile on your C compiler, chances are it is not valid C. – Lundin Mar 18 '15 at 13:26
  • "I have a C code" competes with "it has basically two constructors". thats paradox as in C code isn't anything provided, whats called constructor, or behaves after that concept.;) – dhein Mar 18 '15 at 13:26
  • That was my point exactly, no constructors in C. It might be a C++ code, that makes sense. As source code I only have some headers which are written in C style. – lulijeta Mar 18 '15 at 13:37

3 Answers3

7

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.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
3

There are no constructors in C.

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’
Community
  • 1
  • 1
shauryachats
  • 9,975
  • 4
  • 35
  • 48
0

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.

Sachin
  • 449
  • 4
  • 3