What will happen when I call a member function on a NULL object pointer?

后端 未结 6 1371
闹比i
闹比i 2020-11-22 01:56

I was given the following as an interview question:

class A
{
public:
    void fun()
    {
        std::cout << "fun" << std::endl;
             


        
6条回答
  •  无人及你
    2020-11-22 02:53

    The most likely behavior, on most modern computers, is that it will run, and print "fun", because:

    • C++ doesn't check whether the pointer is NULL before calling the function
    • fun() is not virtual, so there's no need to refer to a vtable to call fun()
    • fun() never access any member variables in A so it doesn't need to dereference the null this pointer.

提交回复
热议问题