+ 1

Is there a way to avoid crash when static cast is used

Hi Refer code below: https://www.sololearn.com/compiler-playground/cZGbHJVaI9b2 Question is related to static_cast... Refer function called Test4. Code line derived* pd = static_cast<derived*>(pb); is trying to convert base class pointer to derived class pointer where base class pointer pb was holding reference of base object So this cast is failed as I have used static_cast.... Now If i am trying to uncomment the code line pd->display1();, it obviously crashes. I know I should be using dynamic_cast, but is there a chance to avoid such crash without using costly dynamic cast? https://code.sololearn.com/cZGbHJVaI9b2/?ref=app

2nd Oct 2022, 10:35 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
5 odpowiedzi
+ 2
I can't click the link in your post. It doesn't seem like a code URL as well, so could you re-post the link to the code.
3rd Oct 2022, 3:21 AM
XXX
XXX - avatar
+ 1
https://code.sololearn.com/cZGbHJVaI9b2 but It doesn't crash for me !? anyway to same class pointer(up/down cast) you must use dynamic_cast and to see if cast was successful you can check if the pointer isnt nullptr
3rd Oct 2022, 8:17 AM
Prashanth Kumar
Prashanth Kumar - avatar
+ 1
Prashanth Kumar thanks I have also updated question text to attach code Just uncomment line 90 and it will crash....
3rd Oct 2022, 8:28 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Ketan Lalcheta To downcast you must use dynamic_cast not static_cast line 85
3rd Oct 2022, 8:52 AM
Prashanth Kumar
Prashanth Kumar - avatar
0
I am already using dynamic cast in test5 function... I just wanted to check is there a way to avoid atleast crash if static cast is used ? Or no way at all or any tweak and it is bound to crash
3rd Oct 2022, 1:41 PM
Ketan Lalcheta
Ketan Lalcheta - avatar