Why this program is not crashing up?
class Test
{
private:
int m_Data;
void Disp( int n)
{
int i = n + 100;
cout << “Data = ” << i;
}
};
int main()
{
Test* t = 0;
t->Disp( 100 );
}
What is the output of this function? Will it crash?
This program outputs Data = 200 Why?
Normally we think program will crash if function call with a null pointer. But if you know the internal working of member function call, it will easy to catch my words.
As you all know, there is only one definition of member function in memory. All the instance of the class uses this memory.
t->Disp( 100 ) will replaced by compiler as Test::Disp( Test* this, int n ) ( Note that every non static member function will have “this” pointer to refer the calling object itself ).
Then this is null pointer and n is 100. Inside the Disp function we just manipulate data that don’t depends the class. So there is no chance for crash.
But if we call member data inside the Disp function, the scene will change, this->m_Data surely crash the program.
No comments yet.
Leave a comment
-
Archives
- September 2008 (1)
- August 2008 (4)
- July 2008 (5)
-
Categories
-
RSS
Entries RSS
Comments RSS