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

后端 未结 25 1664
误落风尘
误落风尘 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:49

    As everyone else notes there are really only two actual language differences:

    • struct defaults to public access and class defaults to private access.
    • When inheriting, struct defaults to public inheritance and class defaults to private inheritance. (Ironically, as with so many things in C++, the default is backwards: public inheritance is by far the more common choice, but people rarely declare structs just to save on typing the "public" keyword.

    But the real difference in practice is between a class/struct that declares a constructor/destructor and one that doesn't. There are certain guarantees to a "plain-old-data" POD type, that no longer apply once you take over the class's construction. To keep this distinction clear, many people deliberately only use structs for POD types, and, if they are going to add any methods at all, use classes. The difference between the two fragments below is otherwise meaningless:

    class X
    {
      public:
    
      // ...
    };
    
    struct X
    {
      // ...
    };
    

    (Incidentally, here's a thread with some good explanations about what "POD type" actually means: What are POD types in C++?)

提交回复
热议问题