When should you use a class vs a struct in C++?

后端 未结 25 1656
误落风尘
误落风尘 2020-11-22 00:18

In what scenarios is it better to use a struct vs a class in C++?

25条回答
  •  被撕碎了的回忆
    2020-11-22 00:48

    As others have pointed out

    • both are equivalent apart from default visibility
    • there may be reasons to be forced to use the one or the other for whatever reason

    There's a clear recommendation about when to use which from Stroustrup/Sutter:

    Use class if the class has an invariant; use struct if the data members can vary independently

    However, keep in mind that it is not wise to forward declare sth. as a class (class X;) and define it as struct (struct X { ... }). It may work on some linkers (e.g., g++) and may fail on others (e.g., MSVC), so you will find yourself in developer hell.

提交回复
热议问题