Reputation: 1278
#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.
Upvotes: 3
Views: 523
Reputation: 69892
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.
Upvotes: 4
Reputation: 726709
The example that you are showing is not a violation of encapsulation, because subclasses are allowed to add public members on top of what they inherit, and they also are allowed to access protected members that they inherit.
In your case, B
, a subclass of A
, decided to add a new member function called func
, whose implementation happens to consist of a single invocation of A::func
.
Generally, protected
members should be regarded part of interface of your class, along with its public
members. Despite the fact that their visibility is limited to subclasses, protected members are not part of the class implementation, because any change to protected members naming or semantics need to be coordinated with changes to all subclasses of the class.
Upvotes: 2