0
#include <iostream>

class Foo
{
private:
    int* ptr;
public:
    Foo()
    {
        ptr = new int;
    }

    void print()
    {
        std::cout << "Hello World\n";
    }
    
};


int main()
{
    Foo* ptr{ nullptr };
    ptr->print();
}

Why is print accessible ?

Print is not a static method, so it's not tied to the class but to the object. Is it because the compiler makes it inline or is it because print's body reside in the code section of the block so it's accessible throughout the program ?

UpAndAdam
  • 4,515
  • 3
  • 28
  • 46
  • it's not a virtual method, so it doesn't need to access the vtable from the pointer. And it doesn't access any member variables through `this`. So it never notices that the pointer is null. – Barmar Aug 28 '23 at 22:37
  • 1
    And, of course, dereferencing `nullptr` takes you to the land of undefined behavior. – tbxfreeware Aug 28 '23 at 22:38
  • 1
    It is undefined behavior, so it is compiler dependent. `nullptr` is one of the most dangerous things in C++ – RedH Aug 28 '23 at 22:42
  • 1
    "Accessible" has a specific meaning in C++. It means whether or not a class member is allowed to be named based on the `private`/`protected`/`public` attributes. That's not what you mean here. You can in fact not call `ptr->print()`. It is not permitted and causes undefined behavior because `ptr` doesn't point to any object. But undefined behavior in C++ does not mean that you will get any error or warning. It simply means that there will be no guarantee at all how the program will behave. Technically it also doesn't matter whether or not the function is `static`. It would be UB either way. – user17732522 Aug 28 '23 at 22:42
  • C++ prizes speed over making sure the programmer didn't do something dumb. If detecting and diagnosing a logic error will take runtime resources, C++ doesn't do it unless you ask it to. – user4581301 Aug 28 '23 at 22:45
  • "_or is it because print's body reside in the code section of the block so it's accessible throughout the program ?_": That's true of all functions, whether member functions or not. They are always compiled and stored in the text section of the binary. They are not somehow stored as part of individual objects. There is no way that they could differ from object to object (in contrast to e.g. Python where this is possible). – user17732522 Aug 28 '23 at 22:51

0 Answers0