문제

I have a function that 2 derived classes use, but the third doesn't, would it make sense to just leave it in the base class, even though one of the 3 derived classes doesn't use it?

The only way I could think of disallowing the third class is to basically create an intermediate class that is derived of the base, then the 2 that use the common function are derived off the second class.

Is it possible to prevent the 3rd class from using the function, while letting the two that are supposed to use it, use it?

Does that just seem to go overboard, I mean as long as I don't "try" to call the function from the 3rd class, it shouldn't be a problem, I just was interested if there was a way to prevent it all together without a lot of hassle.

도움이 되었습니까?

해결책

There is not a way to do this directly. Basically, when you subclass, you're saying the subclass is a more specific version of the base class.

In this case, you're trying to say "the subclass is a more specific version of the base class, except for the fact that it shouldn't be able to touch XXX". That's, in essence, violating the Liskov Substitution Principle.

The best way to handle this is to add a second base class in your hierarchy, which is I believe the solution you mention.

Basically, make your hierarchy:

base
 | \----   subclass without feature available
 |
 \--base+feature
       \--subclass one with specific feature
       \--subclass two with specific feature

다른 팁

You can make this function virtual. Then override the function in the 3rd class and throw an exception. It will prevent developers to use the function in the 3rd class.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top