By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,171 Members | 1,037 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,171 IT Pros & Developers. It's quick & easy.

Test if this is NULL

P: 1
Hi,

some time it would make code easier to check if this is NULL.
For instance, instead of :
Expand|Select|Wrap|Line Numbers
  1. class foo
       {
  2.    int x ;
  3.    void bar () { cout << "my x is " << x ;} // crashes if this is null !
  4.    } ;foo * f = ... ;
  5. if (f) f->bar() ; // so check before to call !
  6.  
It would be nice to write :
Expand|Select|Wrap|Line Numbers
  1. class foo
    {
  2.    int x ;
  3.    void bar () { if (this) cout << "my x is " << x ;} // won't crash if this is null
  4.    } ;foo * f = ... ;
  5. f->bar() ; // call and don't care !
  6.  
Actually, I use this trick already, but my question is :

Will it always work ?
What if the method 'bar' is virtual ?
Is it compiler dependant ?
Is there some thing about this in some holly book of c++ ?

thanks !

Gaspos
Mar 20 '07 #1
Share this Question
Share on Google+
1 Reply


DeMan
100+
P: 1,806
I'm not sure I can see how "this" can be NULL and the "cout" exists at the same time

I believe (and am sure to be corrected if I'm wrong), that NULL is simply a pointer to a magical destination in memory. While I would imagine this is the same on any compiler, it is a good habit (for clarity as much as anything else) to be very explicit with what you are testing and would recommend using something like
if(this == NULL){}
Mar 20 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.