Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is possible to call nonstatic member-function without an object instance? [duplicate]

Tags:

c++

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

Well I think this code and program output explain it self:

#include <iostream>
#include <string>
using namespace std;

class Test
{
public:
    void Not_Static(string args)
    {
        cout << args << endl;
    }
};

int main()
{
    Test* Not_An_instance = nullptr;
    Not_An_instance->Not_Static("Non-static function called with no object?");
    cin.ignore();
    return 0;
}

program output:

Non-static function called with no object?

why is that possible?

like image 819
codekiddy Avatar asked Jan 23 '12 19:01

codekiddy


3 Answers

Undefined behaviour. Your program invokes undefined behaviour by invoking a method on a null pointer, so everything is allowed, including your output.

Remember: C++ language's specification don't specify the output of every possible program to leave room for optimizations. Many things are not checked explicitly and can result in behaviour that seems incorrect or illogical, but is simply unspecified.

like image 157
thiton Avatar answered Sep 20 '22 17:09

thiton


This behavior is undefined - so it is quite possible it will print that output. The issue is undefined behavior can easily bite you, so you shouldn't do such a thing.

like image 42
JonH Avatar answered Sep 22 '22 17:09

JonH


Because it doesn't use this and therefore doesn't dereference null pointer. Make it virtual and it will likely fail.

like image 41
Michael Krelin - hacker Avatar answered Sep 19 '22 17:09

Michael Krelin - hacker