The title is deceptive; the question is really "why does C++ have classes and not only structs?"
Often, people ask why C++ has structs if they are functionally equivalent to classes. The answer is (as in most not-type-safe/not-OOP/not-modern/not-... things in C++), is "inherited from C to not break compatibility". Well.
But if we already have structs from C, and we're planning to add them OOP functionalities (encapsulation, inheritance, methods), why just not remain with them? Why add complexity to the language with redundant keyword class
and introduce confusion about what's the difference between the two?
The only reasons I can think about are:
- Default private accessibility. But anyway the recommendation is to be explicit, is it worth? I think that not.
- Be consistent with other OO languages. I don't know much history about it so maybe there wasn't programming languages that use
class
at that time at all, but even if there was, you're creating a new language!
class
keyword is not particularly necessary or helpful, but it's not like C++struct
has the same meaning as in C wherestruct T
andT
can name different types. In a template parameter list you can saytemplate<typename T>
ortemplate<class T>
but nottemplate<struct T>
.