Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do these two classes violate encapsulation?

class X
{
protected:
    void protectedFunction() { cout << "I am protected" ; }
};

class Y : public X
{
public:
    using X::protectedFunction;
};

int main()
{
    Y y1;
    y1.protectedFunction();
}

This way I am able to expose one of the functions of the base class.

  1. Doesn't this violate the encapsulation principle?
  2. Is there a specific reason as to why this is in standard?
  3. Is there any uses of this, or is it going to be changed in the new standard?
  4. Are there any open issues related to this in the standard?
like image 547
Yogesh Arora Avatar asked Jan 19 '10 15:01

Yogesh Arora


People also ask

Do getters and setters violate encapsulation?

Having getters and setters does not in itself break encapsulation. What does break encapsulation is having a getter and a setter for every data member (every field, in java lingo). That is one step away from making all data members public.

Does friend function violate encapsulation?

A friend function in the class declaration doesn't violate encapsulation any more than a public member function violates encapsulation: both have exactly the same authority with respect to accessing the class's non-public parts.)

Do public variables violate encapsulation?

If a variable is public inside the class, it can be accessed by the client code written outside the class. Hence, instance variables that are declared violate the principal of encapsulation.

Does friend function violates data hiding?

Use of friend functions is rare, since it violates the rule of encapsulation and data hiding. The function can be declared in public or private sections without changing its meaning.


1 Answers

You did it by yourself.
You could write

class Y : public X
{
public:
    void doA()
    {
       protectedFunction();
    }
};

int main()
{
    Y y1;
    y1.doA(); 
}

I don't see any reason to worry about it.
Protected functions are pieces of reusable logic in the inheritance tree. You can hide them if there is some internal logic or restriction or like in your case you can expose it if you are sure that this won't harm anyone.

like image 180
Mykola Golubyev Avatar answered Sep 28 '22 09:09

Mykola Golubyev