C structure and C++ structure
Could anybody please tell me what is the main difference between C & C++ structures.
Solution 1:
In C++ struct
and class
are the exact same thing, except for that struct defaults to public
visibility and class defaults to private
visiblity.
In C, struct names are in their own namespace, so if you have struct Foo {};
, you need to write struct Foo foo;
to create a variable of that type, while in C++ you can write just Foo foo;
, albeit the C style is also permitted. C programmers usually use typedef struct {} Foo;
to allow the C++ syntax for variable definitions.
The C programming language also does not support visibility restrictions, member functions or inheritance.
Solution 2:
In C++, structures behave like classes, allowing methods, constructors, destructors etc...
The main difference between classes and C++ structures is that everything inside structures is public by default, while everything inside classes is private by default. (ie: nothing outside can access them directly)