0

If we see the below code, fun function converts C's object into B's object and calls B' own function. How doesn't it give segm fault. I think this will lead to crash. My program is not crashed. Can any one explains why is it working fine.

#include<iostream> using namespace std; class A{ public: A() {cout<<"A's Con\n"; } ~A() {cout<<"A's De\n"; } }; class B :public A { public: B() {cout<<"B's Con\n"; } ~B() {cout<<"B's De\n"; } void printb(){cout<<"B print function\n";} void printb2(){cout<<"B print2 function\n";} }; class C :public A { public: C() {cout<<"C's Con\n"; } ~C() {cout<<"C's De\n"; } void printc(){cout<<"C print function\n";} }; void fun(A *ap) { B *bp = (B*) ap; bp->printb2(); } int main() { C c; fun(&c); return 0; } 
4
  • Undefined behaviour, anything can happen. Commented Sep 25, 2012 at 17:01
  • proper indentation and proper English would help Commented Sep 25, 2012 at 17:02
  • sry.. I did not concentrate much while writing Commented Sep 25, 2012 at 17:14
  • Hi, how do i do run time typechecking without using dynamic_cast, I dont want to use dynamic_cast , Can I do with static_cast or any other //// Commented Sep 25, 2012 at 18:40

1 Answer 1

2

You're invoking undefined behavior. The first rule about undefined behavior is that anything could happen. Your program might crash, or it might work successfully. It might appear to work successfully and then crash hours later in an "impossible" way. It might even send inappropriate emails to your boss or erase your hard drive. That's certainly unlikely for a random benign error, but if your program is, say, a web browser, it could certainly be exploited to do whatever an attacker might want.

Never rely on undefined behavior. Always fix the underling issues. Use tools like Valgrind, Application Verifier, etc. to help you catch subtle errors that don't always result in crashes. It will make your software much more reliable in the long run.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks alot. We can use static cast after checking typeid of object ( using RTTI) Am i correct ?
Hi... Can any one suggest how to write code for the above requirement

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.