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

后端 未结 6 1571
闹比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:36

    Three points might help:

    1) All Functions are stored in code or text section.

    2) Non Virtual functions are resolved at complie time.

    3) While calling to member functions of class, we pass current object as this pointer to that function.

    Coming to your question , here fun() function is already in memory(code section / text section). As function fun() is non virtual , it will be resolved at complie time (i.e, for this line it will jump to instruction X at code section with this pointer as NULL). As no member variable and no virtual function are used/called in fun() function, it is working fine.

提交回复
热议问题