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

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

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

25条回答
  •  执念已碎
    2020-11-22 01:08

    To answer my own question (shamelessly), As already mentioned, access privileges are the only difference between them in C++.

    I tend to use a struct for data-storage only. I'll allow it to get a few helper functions if it makes working with the data easier. However as soon as the data requires flow control (i.e. getters/setters that maintain or protect an internal state) or starts acquring any major functionality (basically more object-like), it will get 'upgraded' to a class to better communicate intent.

提交回复
热议问题