Strange behaviour - Pointer to an object of a class

Hi guys, I have a strange problem here. Please provide me with an explanation for this. here is the code extract

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

using namespace std;

class A {
private:
	int m_memberVariableX;

public:
	A () {
		m_memberVariableX = 10;
	}

	void memberFunction(int arg_param) {
		cout << "arg_param = " << arg_param << endl;
	}
};

int main() {
	A * l_ptrToA = 0;
	l_ptrToA->memberFunction(10);
	system("PAUSE");
	return 0;
}


isn't the pointer 'l_ptrToA' in the main invalid? the above code when executed shows the result as 10 as expected. So far my understanding was that any functions/member variables called on a pointer initialized to null will result in a segmentation fault!

how does this function work! Also if in the function 'memberFunction' if i display the member variable 'm_memberVariableX' instead of the parameter 'arg_param' the execution results in a segmentation fault as expected, i understand this behavior but not the earlier one!

thanks in advance...
Spaesee
First of all, memberFunction() prints out its parameter, not the value of m_memberVariableX (which also happens to be "assigned" 10 in the constructor), so there is no magic as to why 10 is printed. But the real question is why does the program not crash. You have to understand how the compiler handles member functions.

Although the prototype for memberFunction is
 
void memberFunction( int arg_param )


what really happens beneath the scenes is the compiler passes a second parameter to this function, that parameter being a pointer to the instance of A that you are calling the member function on. (The so-called "this" pointer, essentially). Because memberFunction doesn't actually look at any data members of A, the pointer is not derefenced; it is simply unused. This is why the code above does not crash. This also explains why it does crash if you attempt to print m_memberVariableX, because now you are attempting to dereference the "this" pointer to access the member variable.

You should find that another way to crash this program is to make memberFunction (as it is now) a virtual function. Even though it still doesn't access any data members, it still crashes.

Since I just answered your homework question, I'll leave the answer to my question for you to figure out.
Topic archived. No new replies allowed.