Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

c++ - C-Style upcast and downcast involving private inheritance

Consider the following piece of code :-

class A {};

class B : private A {};

B* bPtr1 = new B;
// A* aPtr1 = bPtr1; // error
// A* aPtr2 = static_cast<A*>(bPtr1); // error
A* aPtr3 = (A*)bPtr1;
B* bPtr2 = (B*)aPtr3;

The C-style cast discards the private inheritance while both the implicit and static_cast fail (also dynamic_cast). Why ? If C-style casts are just bit-fiddling, how are C++ casts implemented i.e. how do they know the type of inheritance from memory footprint?

After bPtr1 is casted to aPtr3, i will have to use another C-style cast to downcast to B as again both static_cast and dynamic_cast fail. So, is bPtr2 guaranteed to be good?

Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The standard states in 5.4.7 that C-style casts can actually do more than any sequence of new-style casts can do -- specifically including casting from a pointer-to-derived to pointer-to-base even when the base class is inaccessible, which is precisely what happens here with private inheritance. (Why this should be allowed, and in particular why it should be allowed only for C-style casts, is utterly beyond me; but it's undeniably allowed.)

So dribeas is right, compilers are obliged to handle the OP's C-style pointer conversion correctly, even when B inherits from multiple base classes. My own testing with MSVC++8 and MinGW confirms his results in practice -- when B inherits from multiple base classes, the compiler will adjust pointers when converting a B* to an A* or vice versa so that the correct object or subobject is identified.

I stand by my assertion that you ought to derive B publicly from A if you ever intend to treat a B as an A, since using private inheritance instead necessitates using C-style casts.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...