Search code examples
c++oopencapsulation

Is Concept of Encapsulation Violated here?


#include<iostream>

class A {
public:
  int a;
protected:
  void func() {
  std::cout<<"protected member"<<endl;
  }
};

class B:public A
{
public:
  using A::func;  //Isn't this violation of encapsulation?
};

int main(){
B b;
b.func();
return 0;
}

Why the above code runs successfully?

Does it not violate the concept of Encapsulation?

Correct me if I am wrong.


Solution

  • This is an interesting question, and I think it highlights an important and often-overlooked aspect of encapsulation in c++.

    My answer is that "yes, encapsulation has been violated, but not where you think". The actual violation was in declaring the method to be protected in the first place.

    Your code demonstrates nicely the problem with the protected relationship with subclasses... they can de-protect you with ease. Another way of saying this is that if you're going to make a member protected, you may as well make it public because in reality protected is public if your subclasses want it to be.

    What does this mean in practice?

    It means that if you make a member function protected, it is forever part of your class's interface. Therefore you must treat is as seriously as you would any other public member function and indeed as if it were a public member function.

    Which is to say that it should be as stateless as possible, with as few preconditions as possible and should you change the implementation, the logical effect on the object as a whole must remain unchanged.