Search code examples
c++polymorphismaccess-specifier

Is it considered good practice to change the protection level of a method?


In other words if I have a class

class A
{
public:
   A() { .. }
   virtual void somemethod() { .. }
};

is it ok to write

class B : public A
{
public:
   B() { .. }
protected:
   virtual void somemethod() { .. }
};

or are there some drawbacks with this approach?


Solution

  • I would say this defeats the purpose of polymorphism, because when you write a function that accepts a polymorphic type, the derived type should work equally well with it:

    void fun(A* a){
       a->somemethod();
    }
    ...
    A* a = new B();
    fun(a); // Shouldn't this work?!
            // According to Liskov Principle, you are doing it wrong!
            // but really who cares, it depends on your justification
            // of a solution to the the problem at hand.
    

    IMHO, it depends on the specific problem you are trying to solve because I don't believe in "always" successful "best practice".