0
#include <iostream>
using namespace std;

struct Base {
    void doBase() {
        cout << "bar" << endl;
    }
};

struct Derived : public Base {
    void doBar() {
        cout << "bar" << endl;
   }
};

int main()
{
    Base b;
    Base* b_ptr = &b;
    Derived* d_ptr = static_cast<Derived*>(b_ptr);
    d_ptr->doBar(); //Why there is no compile error or runtime error?
    return 0;
}

The output of this program is bar\n.

d_ptr is in fact pointing to a Base class while it 's calling a derived class member function.

Is it a undefined behaviour or something else?

Rick
  • 7,007
  • 2
  • 49
  • 79
  • "_Why there is no compile error or runtime error?_" Why should there be? It's, simply, undefined behavior. – Algirdas Preidžius Oct 29 '20 at 02:18
  • Re: "Why there is no compile error or runtime error?" -- just bad luck. The behavior of the program is undefined, and sometimes the result is that the program does just what you expect. Until it doesn't. – Pete Becker Oct 29 '20 at 14:05

1 Answers1

1

Yes, it is undefined behavior.

There is no compile-time error because you used static_cast - this is a way to tell the compiler "I know the type better than you do". You are telling your object is Derived. You lied to the compiler - thus the undefined behavior.

It happened to work because doBar() does not use any Derived members.

Eugene
  • 6,194
  • 1
  • 20
  • 31
  • Ok. But then I add a `int a = 3;` in Derived class and `cout << a << endl;` it in `doBar()`. No error again. It just gives me garbage value. – Rick Oct 29 '20 at 02:30
  • 1
    So "garbage value" is not an error for you? You would like the program to terminate with an error message? That would be defined behavior. Undefined Behavior means the program can do anything. – Eugene Oct 29 '20 at 02:32
  • @Rick -- "undefined behavior" means only that the language definition does not tell you what the program does. It does not mean that bad things **will** happen, just that bad things **can** happen. – Pete Becker Oct 29 '20 at 14:06
  • @PeteBecker Okay :P – Rick Oct 29 '20 at 15:00