Why is there a class keyword in C++?

后端 未结 5 1806
無奈伤痛
無奈伤痛 2020-12-11 15:50

This question came to my mind when I learned C++ with a background of C. Even if there was a struct why did Stroustrup felt it was necessary to introduce the <

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-11 16:05

    Originally, C++ was called "C with classes"

    EDIT:
    Although the following speculation is plausible, the reason for the two keywords was probably practical in nature: by keeping the syntax and semantics of the struct backward compatible, it was possible to introduce C++ into existing programs easily (as opposed to say revisit all structs and add the keyword 'public' to them...).

    [Speculation] The fact that me have two keywords, may possibly be associated with the genesis of the new languge, whereby initially the OO features were exclusively associated with the new keyword, "class". As this matured it was decided that it would be convenient to introduce some OO features to structs as well, and to keep these...

    ...two concepts for two different uses:

    • struct : for typically small, and data-only "objects", with its members public by default. (but which can also be less transparent and have behavior as well).
    • class : for objects typically grouping data and behavior (functions) and with its members private by default, to implement data-hiding, encapsulation and other OO features.

    The struct is for fully or mostly transparent "objects" with no/little data hiding or behavior, in a continuation of its non-object-oriented use (although such transparent constructs have their place in the the broader context of OO programs). Whereby classes, were intended for introducing of data-hiding and other OO practices.

    An alternative may have been to use the struct keyword for both usages, requiring programmers intending it in its 'class' sense to explicitly define the private members. At a time when OO concepts were not broadly understood in the programmers' community (cf other responses in this post) it was probably felt that a separate keyword would better help 'socialize' the new features/concepts.

提交回复
热议问题