开发者

Should I pointer-cast from a private derived class to its base class?

I found this from C++FAQ

Generally, No.

开发者_开发技巧

From a member function or friend of a privately derived class, the relationship to the base class is known, and the upward conversion from PrivatelyDer* to Base* (or PrivatelyDer& to Base&) is safe; no cast is needed or recommended.

However users of PrivatelyDer should avoid this unsafe conversion, since it is based on a private decision of PrivatelyDer, and is subject to change without notice.

How to understand the above words? I don't think the explanation is correct or accurate.

I have a code like this

class A{
};

class B: private A{
};

int main(){

    B *b = new B();
    A *a = new A();

    a = b;                    //wrong
    a = (A*)b;            //right

}


From a purely mechanical viewpoint, you're right: a cast to a private base class will work and produce working results.

The point of the FAQ is that from a design viewpoint it's generally wrong. Private inheritance is really supposed to mean private -- in other words, even though it may work, you're not supposed to know it'll work, and at some point it may quit working -- since it's officially an implementation detail, not part of the public interface, they could re-implement the class without using inheritance. At that point, the cast wouldn't work any more (but because you've used a cast, the compiler probably won't warn you about it having gone from something you probably shouldn't do to something that can't possibly work at all).

Edit: Yes, the cast does necessarily work. According to §5.4/7 of the standard:

... the following static_cast and reinterpret_cast operations (optionally followed by a const_cast operation) may be performed using the cast notation of explicit type conversion, even if the base class type is not accessible:

— a pointer to an object of derived class type or an lvalue of derived class type may be explicitly converted to a pointer or reference to an unambiguous base class type, respectively;

[emphasis added]


I think that the explanation is correct. It says that even though a cast is possible from B to A it should not be done. The reasone is that the inheritance is private and should be considered an implementation detail of B that the users of the class should never care of. It is just the same rules as anything marked private - it should be considered internal to the class. Outside clients should only rely on the public functions and attributes - including publicinheritance.

Personally I have never found any use for private inheritance - I think that it is often better to use composition.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜