0

I set the pointer to class to nullptr but when I access member function is still works


class A{
public :
    void f1(){std::cout << "Hello, World!" << std::endl;};
    virtual void f2(){std::cout << "Hello, World!" << std::endl;}
};

int main() {

    A* a = nullptr;
    a->f1();
    a->f2();


    return 0;
}
Dilnar
  • 59
  • 2
  • 3
    Calling methods via a `null` pointer is **undefined behavior**. However, your methods don't access any class data members, so the value of the `this` pointer inside the methods is irrelevant. Make the methods access a class member, particularly a dynamically allocated one like a `std::string` or `std::vector`, and then they will be more likely to crash the way you are expecting. – Remy Lebeau Aug 28 '19 at 01:03
  • 2
    Welcome to Undefined Behaviour. One of the worst outcome - program seem to be working and produce expected result. – Slava Aug 28 '19 at 01:03
  • lol now can I ask how do you know all this cool things :) – Dilnar Aug 28 '19 at 01:07
  • 1
    @Dilnar programming by guessing does not work, especially on C++ - you need to know what you are doing. Calling method on `nullptr` is UB according to the language standard. – Slava Aug 28 '19 at 01:09
  • 1
    @Dilnar You read [good books](https://stackoverflow.com/q/388242/9254539). – eesiraed Aug 28 '19 at 01:21

0 Answers0