Search code examples
c++polymorphismcompiler-optimization

What happens exactly when casting from a base class to derived one?


In the below code, why does the compiler agree on casting a base class to a derived class knowing the object is purely a base one? How can print2() be called although it's a derived function? Can you tell me please what happens exactly from the point of view of a compiler/memory manager?

#include <iostream>

using namespace std;

class Base {
public :
    virtual void print(){
        cout << "Hello from Base" << endl;
    }
};

class Derived : public Base {
   public:
       void print(){
          cout << "Hello from Derived" << endl;
        }
    
       void print2(){
         cout << "Print2" << endl;
       }
 };

 int main()
{
   Base * b = new Base();
   Derived * d = static_cast<Derived *>(b);
   d -> print2();
}

Solution

  • This is undefined behavior, no diagnostic required.

    A compiler has no obligation to report a compilation error for every possible programming bug. The only required diagnostic is when the program is ill-formed.

    There's nothing technically wrong with the static_cast itself, with that statement alone. It follows all the requisite rules. The fact that it is used improperly, and results on the undefined behavior due to an earlier statement does not require an error message from the compiler. The new statement, and the static_cast itself could be in completely separate .cpp files (with a function call in between, one function calling new, and passing the result as a parameter to the function in the other .cpp file that does the static_cast). This is logically identical to the shown code. How could the compiler possibly be able to report an error, when it's compiling the other .cpp file, and has no knowledge of what's happening in the first one?

    It is true that some compilers might be able to detect this bug and issue a warning message (possibly only with certain optimization levels enabled), but there is no obligation to do so.