Search code examples
c++classencapsulation

C++ encapsulation, how is it useful


The following slide refers to C++ language and it says that

"encapsulation is about ensuring the user uses our ADT in a safe way"

But, If he have access to my .h files he can edit it for example and change what was declared inside my class from private to public.

for example:

my_file.h:

class Complex {
private:
    double re, im;
public:
    double get_re();
};

then the user could write: (after changing from private to public)

Complex s1;
s1.re=13;

Please Click the following link to view the image (Since I don't have point to include images): enter image description here


Solution

  • With C++ you can shoot into your foot in a lot of ways. You can also use

    #define private public
    

    and you won't need to change anything in the code to access the private interface... the point here is not how encapsulation can be broken, instead is about what you achieve using that.

    When you have to choose between class and struct, you have to think if what you are going to represent with that, and if that thing has an invariant, then you should use a class, otherwise a struct: encapsulation will let you achieve that "invariant" using encapsulation, and so letting the user access the data, or set/modify the data only using public interfaces you have defined, and not how he wants.

    For example, if you define a class Date, you have an invariant like "max 31 as day, max 12 as month ...", but if you want to define for example DifferenceInDays, which will have just an int for the days, than you can allow user to read and write whatever he wants in that struct, because you don't have any invariant