Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

I was given the following as an interview question:

class A { public:     void fun()     {         std::cout << "fun" << std::endl;     } };  A* a = NULL; a->fun(); 

What will happen when this code is executed, and why?


See also:

  • When does invoking a member function on a null instance result in undefined behavior?
like image 596
Rajendra Uppal Avatar asked Mar 28 '10 15:03

Rajendra Uppal


People also ask

What happens if you call a NULL function pointer?

Initializing a pointer to a function, or a pointer in general to NULL helps some developers to make sure their pointer is uninitialized and not equal to a random value, thereby preventing them of dereferencing it by accident.

Which pointer is not passed to member function?

The 'this' pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. 'this' pointer is not available in static member functions as static member functions can be called without any object (with class name).

How do you call a pointer to a member function?

Using a pointer-to-member-function to call a function Calling the member function on an object using a pointer-to-member-function result = (object. *pointer_name)(arguments); or calling with a pointer to the object result = (object_ptr->*pointer_name)(arguments);

What is pointer member function?

Pointers to members allow you to refer to nonstatic members of class objects. You cannot use a pointer to member to point to a static class member because the address of a static member is not associated with any particular object. To point to a static class member, you must use a normal pointer.


1 Answers

It's undefined behavior, so anything might happen.

A possible result would be that it just prints "fun" since the method doesn't access any member variables of the object it is called on (the memory where the object supposedly lives doesn't need to be accessed, so access violations don't necessarily occur).

like image 163
sth Avatar answered Sep 24 '22 23:09

sth