1

have a doubt regarding method calls from a class variable that points to a nullptr, I expected it to cause segv but it passed and SEGV was observed only when i tried accessing a class variable through th null ptr object. Wanted to know how does it gets to a function if class variable basically points to null which should have failed

#include <bits/stdc++.h>
using namespace std;

class A {

public:
 void func() {cout << "here";}
 int x;
};

int main()
{
    shared_ptr<A> a;
    a->func(); // passes without any error even though a is nullptr 
    //cout << a->x; this causes SEGV expected
    return 0;
}

My expectation was that it should have failed in a->func() but it passed that, how does it work ?

  • 1
    Undefined behaviour. Just don't. – Quentin Oct 22 '19 at 13:58
  • 1
    Though the call is succeeding without fail, it isn't guaranteed to do so every time. The reason it is working is the function is non-virtual and doesn't access any instance variable, so with a NULL `*this` pointer as well it will have no impact. Remember: 'The worst possible outcome of undefined behavior is for it to do what you were expecting' – Sisir Oct 22 '19 at 14:11

0 Answers0