Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top