简体   繁体   中英

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?

The main drawback with that approach is that one can always take a pointer/reference to A and invoke somemethod where is public. Why would you want to do such thing? If B is an A , and A s have a public somemethod then so do B s.

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".

There is no drawback with this approach. The only limitation is that B::somemethod() cannot be called with B object/pointer/reference. It can be now invoked only using A 's pointer or reference.

In fact, I have seen that sometimes this limitation is introduced intentionally. Such scenarios are when the developer of class B wants to convey the message that, somemethod() is meant to be called only polymorphically using base class handle.

No drawback.

But no real advantage to do this.
You still have accesses to somemethod() via a pointer to the case class.

So no drawback and no advantages on the technical side.
So now we move onto how easy it is to use you object. Here there is a downside as you are confusing the user of the object (why is it protected at this level but not the lower level)? So you are creating work for yourself in documenting why you made this decision and what you are trying to achieve by using this technique.

What is it that you really trying to achieve?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM