Wednesday, 1 August 2007

Accessing non-static member function without object!

We know that we can call a static member function with in a class without instantiating that class. But how about a non-static member function?

Its possible too, unless we try to access any of the member variable within that function.

class CTest
{
public:
    void func()
    {
        cout<<"I can execute even without an object!"<<endl;
    }
};

int main()
{
    CTest *p = 0; // NULL pointer
    p->func();     // Calling member function

    return 0;

This compiles and works fine.

But beware! We must not try to access any of the member variables within that because this pointer will be pointing to NULL.

Remember there was an article about how a member function call is made?

Cheers!

2 comments:

Janani S said...

Hi Prashant,

This article of yours helped me tremendously. But can I know how it works logically ? How can a NULL pointer be used to call a member function? If the same code is used in C, it crashes, but in C++ it doesn't! How ? Shouldn't the pointer have a valid address location before it can be referenced to a pointer?

Janani S said...

Sorry for the typo in the last line of the previous comment. I meant "Shouldn't the pointer have a valid address location before it can be referenced to a function?"