Search code examples
c++classoopencapsulation

When should we encapsulate codes to be a "Class"?


I looked back on my code so far and found that I rarely wrote class. Or, in other words, I don't see the value of using them. I mean, almost everything in coding, I can work them out without using classes by just writing functions and group them into different .h/.cpp files based on their functionalities.

Even after I've participated in several projects, I still do not feel the urgency to do this as progress goes well without big challenges. I am working mostly with C++ (MATLAB sometimes).

Note that, I did use struct a lot and I know that struct and class have no big difference for C++. But I only use struct for data-storage (group data together). The data requires no flow control (i.e. getters/setters that maintain or protect an internal state) nor starts acquiring any major functionality.

Maybe I am missing somewhere about basic things about OOP. So when should we encapsulate our codes using classes? Can anyone share your opinions?


Solution

  • In C++, a struct and a class are just the same except with a different default access modifier. struct members are by default public, whereas class members are by default private. If we think of classes in C++ as being a class with encapsulated data members and public member functions that expose functionality related to that data, the following are some good suggestions that you want to use a class:

    1. You need to store some state consisting of related items of data, and...
    2. You need to impose some invariants on this state or provide some alternative interface to this state.

    If you have only suggestion 1, then you probably just want a struct. See Classes Should Enforce Invariants.