Introduction
A really popular question of the C++ interview is about the difference between struct and class. It seems to be an easy question, but there are multiple views to be considered.
Historical background
Let’s start with the historical view. C++ is based on the programming language C, which is not supporting the object oriented programming paradigm. So that there were no classes in C, only structs. And struct was nothing else than a data structure to be used to store variables of different types together.
Later on with C++ together with the object oriented programming support the keyword class has been introduced to represent the typical object oriented classes.
In C++ Struct has also been extended with time, so it is also possible to inherit structs from each other, change the visibility of the attributes and to add constructors, destructors and member functions.
Technical difference
What is then the exact difference?
Technically there’s only one difference between structs and classes: in a struct the default visibility is public, since in a class the default visibility is private.
There’s technically no other difference in C++.
Practical difference
The difference is more philosophical.
As I already mentioned struct is a collection, a record of data, which belongs somehow together. And nothing more.
Since class is a bit more, class represents something, which has an interface, a state and a behavior. The state is usually internal, not visible from outside, that’s why the default visibility is private. The state can be changed through the predefined interfaces, which are the public methods of the class. Furthermore the usually the class has an invariant which is a restriction on its possible states. In case of a class you have methods which are handling the attributes of the class together.
So my suggestion is: use struct if you need a simple data container of data which belongs together and use class for everything what is more complex, what involves more abstraction.
No comments:
Post a Comment