Variable pointer is declared null, but member function normally executes

9

Below is an example of the code I'm trying to execute.

//main.cpp

#include <iostream>

using namespace std;

class A{
public:
    A(){}
    ~A(){}
    void teste(){
        cout << "Teste" << endl;
    } 
};


int main(){
    A *pA = NULL;

    pA->teste();
    return 0;
}

//end main.cpp

Since I declare the *pA pointer as null, I expected the program to give this error. However, it does so normally and displays the message "Test".

Why does the program run normally instead of throwing an error to type null pointer exception ?

I'm using the Qt5 platform on Linux.

    
asked by anonymous 28.09.2014 / 14:17

1 answer

9

Why do you think you should give an exception?

The pointer is needed to refer to a data structure, that is, to a state, to data in memory. To access the behavior of the class, that is, its methods. the pointer does not need to refer to any memory location. By the type the compiler knows where is the code of the methods that are independent of the instance.

The code stays in a static (fixed) area in memory and progressively the compiler with the linker , and then the load of the executable by the operating system will determine the address of the code. The methods are always available in the application, even if you did not create a valid instance.

It could still generate a exception within the method if it were trying to access some state of the class. But in this case it is not, so you do not have to make a mistake.

What you are prompted to do is to call the teste() method of type A which happens to be referenced by the pA variable but since the class has no data, nothing needs to be stored in memory for execution. If nothing needs to be stored, you do not need to have any memory addresses to refer to, so a NULL drops well. And as during the execution of the method you only access a stream by sending a literal string and the end of the line does not access any instance data which does not exist), does not need to access anything in memory, does not need a valid address in the variable.

So the logical thing is. It would be strange if an exception were thrown. Try to create a stateful field in the class and access it in teste() or directly in main() and see what happens.

In C ++ there is no need and it is not recommended to create stateless classes, prefer to use simple functions and if you need to organize related functions in a single logical unit use namespace . C ++ is not Java.

Do not forget to read the supplement in Guilherme Bernal's commentary below on undefined behavior that is highly undesirable (behavior, not Guilherme's comment :)). It is very important.

    
28.09.2014 / 14:29