Structs and Classes in C++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Structs and Classes in C++

What is the point of the existance of both classes and structs in C++ while in their functionalities are similar ,and the only little difference is the default visibility ? why not creating only structs or only classes ?

28th Jun 2021, 12:20 AM
Ayoub
Ayoub - avatar
6 Answers
+ 6
The only technical difference between struct and class is the default visibility mode ( in struct, all the members are public by default whereas in class they are private by default ). Also while inheriting, structs defaults to public inheritance while classes defauts to private. So the choice of which one to use totally boils down to your programming style. I think the only reason for struct to exist in C++ is to support backwards compatibility for C, that's why in most of the programs I have worked with, I have seen struct being only used as a POD structure ( or C style structure ) and rarely as a class with flipped access specifier. More details about POD types here 👇 https://en.m.wikipedia.org/wiki/Passive_data_structure
28th Jun 2021, 1:21 AM
Arsenic
Arsenic - avatar
+ 1
classes are more advanced than struct... struct only hold values classes are blueprint to create object instances wich have properties (values) and methods (function attached and specific to that object)
28th Jun 2021, 12:26 AM
visph
visph - avatar
+ 1
you could use only classes (as they could act only as a struct), but in case of 'only struct', classes are oversized in memory and (final) code complexity ^^
28th Jun 2021, 12:28 AM
visph
visph - avatar
+ 1
There might be no definite reason why both classes and structs exist as the creators probably didn't explain it, or did they? We only know that the difference between them is default member access. My guess is struct exists for capability of C, and class exists for oop concepts. One thing you should also aware if you learn C is that struct in C is much different from it is in C++ since C is not oop. There is no pros and cons to choose one over the other, but I advise that don't mix them in a project unless your team knows when to use one and the other as their default member access are different.
28th Jun 2021, 4:04 AM
你知道規則,我也是
你知道規則,我也是 - avatar
0
structs exist for compatibility reasons. for example if you wrote an emornous c code that will take a decade to replace structs with classes to make it more cpp-y, it would be much easier to compile the code using c++ and gradually change the structs to classes over the years than just release a c++ version after decades of changing all the structs to classes.
28th Jun 2021, 8:12 AM
Bot
Bot - avatar
0
however in the c ++ course there are no lessons on structs. if there is the possibility to use them was not the case to put them in the course?
13th Feb 2022, 9:01 PM
Makko kola
Makko kola - avatar