+ 1
Why static cast do not allow upcasting for private inheritance
Hi Refer code below: https://www.sololearn.com/compiler-playground/c130CUy32g3e Why static cast throws error? What is that static cast trying to prevent? In other words, C style casting allows but not static cast? What issue we will face if it was allowed to cast like we had in c style casting?
2 odpowiedzi
+ 1
according to iso cpp ( https://isocpp.org/wiki/faq/private-inheritance#priv-inherit-like-compos )
"private inheritance is a syntactic variant of composition (AKA aggregation and/or has-a)"
Meaning only the privately derived class (privateChannel in this case) would be knowing about the relation between the classes, making an attempt to cast ( both implicit cast and static_cast ) privately derived class pointer to base class outside the derived class illegal as it would be similar to casting pointer pointing to 2 different unrelated types. ( you can still perform the cast inside the privately derived class though, see this for example -> https://code.sololearn.com/cevFk481G11S/?ref=app )
This also explains why C-Style cast and reinterpret_cast <> still allows it as they allow you to cast to just about anything ( even if the pointer point to totally different types ) assuming that the developer knows what they are doing.
0
I got your point that its kind of composition Arsenic
But my query is like why so ?
1. Why private inheritance makes it like composition nd public inheritance dont makes it like compositon?
2. I get that reinterpret_cast is on unrelated types and doing so may result into undefined behaviour or failure or crash... so c style casting allowing it might result into failure when we access the pch casted from private channel... right ? Interested to know that scenario as below works fine with casting on private inheritance.
What would have failed if we used c style cast to get base channel pointer ? Then it makes sense to stop this by static cast as compile time error is better than runtime error after c style casting
https://code.sololearn.com/c3iFr32CuEt3/?ref=app