0

Consider the below class :

class Test
{
public:
    void Func1()
    {
        cout << "Func1 called";
    }

    virtual void Func2()
    {
        cout << "Func2 called";
    }
};

int main()
{
    Test* test = NULL;
    test->Func1();
    test->Func2();
}

this does not print anything , however if call to Func2 is commented , it prints "Func1 called"

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • 2
    Are you familiar with the concept of "undefined behavior"? – Nate Eldredge Sep 20 '21 at 02:18
  • 3
    See: [Undefined, unspecified and implementation-defined behavior](https://stackoverflow.com/q/2397984/3422102) and [What is indeterminate behavior in C++ ? How is it different from undefined behavior?](https://stackoverflow.com/q/11240484/3422102) and [Undefined behavior](https://en.cppreference.com/w/c/language/behavior) – David C. Rankin Sep 20 '21 at 02:18
  • No question was asked, but given this clear undefined behavior, the answer is "Anything can happen". Were you hoping something different would happen? – Drew Dormann Sep 20 '21 at 02:19
  • What **may** happen with **some** implementations is that the function is called, with its `this` pointer set to NULL. If you don't dereference `this` or access any member variables, it **may** "work". That does not mean it is correct code - it could easily fail in unexpected ways on other implementations, or with minor unrelated changes to the code. Just don't do it. – Nate Eldredge Sep 20 '21 at 02:19
  • Dunno what the poster was expecting to happen instead... but whatever it was, the expectation was incorrect :) – Jeremy Friesner Sep 20 '21 at 02:19
  • 1
    @drescherjm There are UB canonicals (see David's comment above), but the causes of UB are many, and so using a single (or one of a few) duplicate targets is not ideal. Fortunately, there are targets for many of the causes, especially the common ones. – cigien Sep 20 '21 at 02:48

0 Answers0