开发者

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

In other 开发者_C百科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 As have a public somemethod then so do Bs.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜