Pointer to Class prb

V

Venkatesh

Hi All,

I tried the following code and it seems to work. I am really confused
as to
how this is possible. Can someone please throw some light?

#include<iostream>
using namespace std;

class Y
{
public :
void foo()
{
cout << "Hello World"<< endl;

}
};

main ()
{
Y *ptr = NULL;
ptr->foo();
}

Out put is
Hello World

Thanks in advance.
 
R

Rolf Magnus

Venkatesh said:
Hi All,

I tried the following code and it seems to work. I am really confused
as to how this is possible. Can someone please throw some light?

Shouldn't even compile, because main is missing a return type.
#include<iostream>
using namespace std;

class Y
{
public :
void foo()
{
cout << "Hello World"<< endl;

}
};

main ()
{
Y *ptr = NULL;
ptr->foo();
}

Out put is
Hello World

Thanks in advance.

What exactly does confuse you about the output? Dereferencing a null
pointer invokes undefined behaviour, and perfect functioning is one
instance of undefined behaviour. It's not as surprising as you might
think, since your member function doesn't access any part of your
object and thus the null pointer might never actually get used
internally.
 
K

Karl Heinz Buchegger

Venkatesh said:
Hi All,

I tried the following code and it seems to work. I am really confused
as to
how this is possible. Can someone please throw some light?

#include<iostream>
using namespace std;

class Y
{
public :
void foo()
{
cout << "Hello World"<< endl;

}
};

main ()
{
Y *ptr = NULL;
ptr->foo();
}

Out put is
Hello World

It is undefined behaviour. That means: Anything can happen
and that includes works as expected or crashes the machine.

On a deeper level, what is most likely happening (details
vary from compiler to compiler).

When you define a member function, the compiler arranges
things that the function is just like any other freestanding function
with an additional parameter: the object for which it is called on.

so the compiler transforms you foo() function into:
void foo( Y* this )
{
cout << "Hello World" << endl;
}

and it also transforms the call in main into:

int main()
{
Y *ptr = NULL;

foo( ptr );
}

So you now see why nothing special is happening: While the passed
pointer to foo() is NULL, it is never used in any way, thus nothing
special happens.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top