Click here to Skip to main content
16,021,125 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Maybe I have been staring at the screen too long today, because I'm not sure if I am seeing this correctly. Here is the code I am looking at:

C++
#include <iostream>
using namespace std;

class SomeClass
{
    public:
    void f();
};

void SomeClass::f()
{
    cout<<"in some class"<<endl;
}


int main()
{
    SomeClass* sc;
    sc = NULL;
    sc->f();

    return 0;
}




And here is the output:


in some class



why am I getting this output?
Posted
Updated 20-Jun-13 16:05pm
v2

1 solution

To understand it, you should understand how instance functions are called. Your function f has zero parameters, but one hidden parameter is still passed implicitly: "this", a pointer to the instance of the class; in this case, this is sc.
This "this" is used to access other instance members of the class.

In your case, sc happened to be null. So what? It generates the code which passed null as a parameter. But it is not used! Functionally, your function is similar to the static function, which does not need an instance for a call. In your case, the generated code calls the class method and passes null, which changes nothing. The call is successful.

In other words, you never really dereference sc, as it is not needed to generate a function call, and the body of the method does not do anything which would try to dereference null. Of course, this is a kind or C++ weirdness, but quite explainable.

You don't have to do something similar in practice, of course. In practice, a method like this should be declared static.

—SA
 
Share this answer
 
Comments
Ron Beyer 20-Jun-13 22:50pm    
+5
Sergey Alexandrovich Kryukov 20-Jun-13 23:51pm    
Thank you, Ron.
—SA
H.Brydon 20-Jun-13 23:22pm    
+5 from me too.

You almost said it but you can also reference public static methods and data through a null pointer in this fashion...
Sergey Alexandrovich Kryukov 20-Jun-13 23:54pm    
Thank you, Harvey.

Do you mean something like this
static int EquivalentFunction(SomeClass* instance);
functionally equivalent function?

If instance is null, the implementation my avoid dereferencing it, exactly as with "this"...

—SA
H.Brydon 21-Jun-13 0:24am    
class SomeClass
{
public:
static void f(){ st = 42; }
static int st = 0;
};

int main()
{
SomeClass* sc = NULL;
sc->f();
SomeClass::f();
sc->st = 7;
SomeClass::st = 8;

return 0;
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900