Why is there a class keyword in C++?

As David says, structs are public by default, classes are private by default. The larger point is that adding object orientation to C was a big change, and giving developers ways to express themselves accurately is an important part of designing a language.

As it turns out, the distinction between struct and class is quite minor from a technical point (default-public vs default-private), but in programmers' minds, the distinction is quite large. Adding the keyword was an important way to emphasize the OO nature of C++.


In The Design and Evolution of C++, while describing how C++'s object model and virtual functions were developed, he writes (p. 76):

At this point, the object model becomes real in the sense that an object is more than the simple aggregation fo the data members of a class. An object of a C++ class with a virtual function is a fundamentally different beast from a simple C `struct`. Then why did I not at this point choose to make structs and classes different notions?

My intent was to have a single concept: a single set of layout rules, a single set of lookup rules, a single set of resolution rules, etc... I was convinced that if `struct` came to mean "C and compatibility" to users and `class` came to mean "C++ and advanced features," the community would fall into two distinct camps that would soon stop communicating. Beingn able to use as many or as few language features as needed when designing a class was an important idea to me. Only a single concept would support my ideas of a smooth and gradual transition from "traditional C-style programming," through class abstraction, to object-oriented programming. Only a single concept would support this notion of "you only pay for what you use" ideal.

So it sounds like the class keyword was introduced to indicate C++-specific object orientation and then its compatibility with the struct keyword was introduced.

Tags:

C++