Reputation: 573
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;
}
Upvotes: 0
Views: 117
Reputation: 400156
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.
Upvotes: 2