Search code examples
c++encapsulation

Is encapsulation violated, if I use a global variable in a class member function's definition?


I've been asked to explain what encapsulation is and I replied "bundling of data and functions that modify this data, is called encapsulation."

The answer was followed by another question—"So, by your definition if I modify a global variable from a member function of a class then the encapsulation is violated."

It made sense to answer YES.

I am not sure whether my explanation is wrong or following question is valid and my answer to it as YES is correct.

Can somebody help.


Solution

  • Quoting from wikipedia:

    In programming languages, encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination thereof:

    • A language mechanism for restricting access to some of the object's components.
    • A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data

    In my humble opinion the answer to the follow up question is subjective and it depends on the interpretation of the notion of encapsulation.

    For example it's not a violation if the encapsulating data are limited to be the member variables of classes. A global variable that doesn't belong to an object is accessible by everyone and thus, accessing it via a member function doesn't consist any encapsulation violation.

    On the other hand if you consider that encapsulation should be applied to your entire program then this global variable should have been bundled to an object and thus, raw access to it constitutes an encapsulation violation.

    The bottom line is that the answer lies in the realms of theology, meaning that it depends on how encapsulation is interpreted by the different programming dogmas.