strenge behaviour

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

#include <iostream>
#include <exception>
using namespace std;

class CBase { virtual void dummy() {} };
class CDerived: public CBase { int a;
	public:
		void show()
		{
			cout<<"here\n";
		} 
	};

int main () {
  try {
    CBase * pba = new CDerived;
    CBase * pbb = new CBase;
    CDerived * pd;

    pd = dynamic_cast<CDerived*>(pba);
    if (pd==0) cout << "Null pointer on first type-cast" << endl;

    pd = dynamic_cast<CDerived*>(pbb);
    if (pd==0) cout << "Null pointer on second type-cast" << endl;
 
 			cout<<pd<<endl; //shows null
    	pd->show(); // works ???? !!!!!!

  } catch (exception& e) {cout << "Exception: " << e.what();}
  return 0;
}


i am running above code on unix environment having aCC compiler
even pointer has null value in it call to show is successful how ?

thanks in advance
Hi,

I believe this will answer your question:
http://stackoverflow.com/questions/669742/accessing-class-members-on-a-null-pointer

See the Question and Accepted Answer.

- Tom
You don't need to dereference the this pointer to call a non-virtual member function.
So the this pointer can be 0

You do need to dereference the this pointer to access the object's non-static variables and virtual functions.
Last edited on
thanks , it really helps
but i got another problem

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

using namespace std;

class X
{
private:
	int x;
public:
void dispX()
{
	x = 1;
	cout << x << endl;
}
};

int main()
{
X* ptr = 0;

ptr->dispX(); // fails

return 0;
}


why this fails ??
is it because of int x ?
is it because of int x ?
Yes. That's what guestgulkan tried to explan. If you have an invalid pointer to a class and you want to access the member variable (no matter if directly or through a function) it will crash
Topic archived. No new replies allowed.