Different between struct and classes in c++? | Sololearn: Learn to code for FREE!

+4

Different between struct and classes in c++?

11/26/2021 2:44:09 PM

Ali Ibtisam

5 Answers

New Answer

+7

In C++ there isn't a big difference between those except their default access specifiers ( for class it's private and for struct it's public ) But I have rarely seen structs being used as classes with flipped acess specifiers but more like "C-style" structs ( POD type ).

+5

Lisa The webpage you've linked has a lot of incorrect information "The structure will automatically initialize its members. In contrast, constructors and destructors are used to initialize the class members" Incorrect, event structs can have constructors and destructors and even classes will default construct its members when no constructor is defined "When a structure is implemented, memory allocates on a stack. In contrast, memory is allocated on the heap in class" Incorrect, all objects in C++ go on the stack unless they are initialized on the heap using the 'new' operator "Variables in a structure cannot be initialized during the declaration, but they can be done in a class" Yes they can be initialized during declaration in structs "There can be no null values in any structure member. On the other hand, the class variables may have null values" C++ has no null values. There is only nullptr which can only be assigned to pointer types. So god knows what "null values" can be assigned to class properties

+3

[Continued] "A structure is a value type, while a class is a reference type" Incorrect, there are no value types or reference types in C++. A reference is passed when the function or variable wants a reference, else the object is passed by value What were they even thinking while writing the page? It feels like it was written by someone who knows Java and has just gone through a basic C++ tutorial. One can't even ask people to google something if information like this is what comes up as search results As @Arsenic said, classes and structs in C++ have no difference except for the default access specifiers.

+2

Joe All the features of classes that you described apply to structs as well. Structs can be inherited, can contain member functions, etc. I think you might be comparing C++ classes to C structs.

0

There are many differences… too many to list. Classes can be derived and inherited from other classes, they can contain member functions, you can overload operators in classes, and probably the biggest difference is being able to keep classes in their own header file for reuseability. Obviously structs have their place for keeping data, but beyond that you want to use a class.