1

Consider the following sample code.

#include <iostream> using namespace std; class base { public: void func() { cout << "base::func()" << endl; } }; class derived : public base { public: void func() { cout << "derived::func()" << endl; } }; void dummy(base *bptr) { derived *dptr = static_cast<derived*> (bptr); dptr->func(); } int main() { base bob1; derived dob1; dummy(&dob1); //Line1 dummy(&bob1); //Line2 } 

In Line1, I am passing the address of a derived class object to function dummy which takes a pointer to base class object. So the static_cast in the function dummy is safe.

In Line2, I am passing the address of a base class object to function. So the static_cast in the function dummy is not safe.

But when i execute the code, the program behaves normally. I thought, by the word not safe, the program should crash at run-time. But no crash occurred.

Here is the output which i get.

derived::func() derived::func() 

What is the reason why the program did not crash at run-time?

4
  • Bad code is much harder to understand than good code. Commented Jul 18, 2012 at 9:19
  • @ David : Could you please elaborate? Commented Jul 18, 2012 at 9:22
  • possible duplicate stackoverflow.com/questions/2469013/… Commented Jul 18, 2012 at 9:25
  • @LinuxPenseur: Understanding bad code requires a very deep understanding of the implementation decisions made by the compiler. Good code is carefully constructed to have behavior independent of those decisions. Commented Jul 18, 2012 at 9:31

2 Answers 2

10

Because undefined behavior means anything can happen, not necessarily a crash.

On most compilers I've seen, calling a non-virtual method that doesn't access class members on a NULL pointer works, but it remains undefined.

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

Comments

6

One of the core concepts of C++ is undefined behaviour. When you perform an operation that results in undefined behaviour, e.g. static-casting a pointer that doesn't point to an object of the casted type, the behaviour of your program is literally undefined: The standard does not define any specific behaviour. The platform is not required to do anything specific, any behaviour it shows is OK according to the standard.

This undefined behaviour includes silently doing what looks like normal behaviour to you. There is no guarantee for a segmentation fault or any other diagnostic.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.