-
December 17th, 2004, 11:42 AM
#1
Why and How it is working.
Hi friends
Please read the following code.
Code:
#include <iostream.h>
#include <conio.h>
class alpha
{
public :
alpha()
{
cout << endl << "Constructor called ...";
}
void showalpha()
{
cout << endl << "This is alpha class ...";
}
};
void main()
{
clrscr();
alpha *a = new alpha();
alpha *b = NULL;
a->showalpha();
b->showalpha();
cout << endl << "Value in a = " << a;
cout << endl << "Value in b = " << b;
getch();
}
Output of the above program is :
Constructor called ....
This is alpha class ...
This is alpha class ...
Value in a = 0x90500004
Value in b = 0x0
Actually *b contains NULL value then how it's calling showalpha() and how it's working fine.
Can any body pls explain to me.
-
December 17th, 2004, 11:53 AM
#2
Re: Why and How it is working.
It works since the code in showalpha doesn't try to access any member variables.
Hope this help.
-
December 17th, 2004, 06:13 PM
#3
Re: Why and How it is working.
However, the program is incorrect and this behaviour should not be relied upon.
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
-- Sutter and Alexandrescu, C++ Coding Standards
Programs must be written for people to read, and only incidentally for machines to execute.
-- Harold Abelson and Gerald Jay Sussman
The cheapest, fastest and most reliable components of a computer system are those that aren't there.
-- Gordon Bell
-
December 17th, 2004, 06:38 PM
#4
Re: Why and How it is working.
FYI:
iostream.h is not part of the C++ standard, and should not be used in any new code.
Use extensionless version <iostream> which is part of the standard.
-
December 17th, 2004, 08:45 PM
#5
Re: Why and How it is working.
To add to what the others said:- It works because the function's this-pointer is never dereferenced - as marten_range said, as long as you don't access a member variable or call a member function which does so, that kind of call will most probably work due to the way function calls are implemented in most compilers.
- However, as Graham said, calling a member function through a NULL (or otherwise invalid) pointer is considered undefined by the standard. You might encounter a compiler where that code fails.
- As a sidenote: MFC relies on the feature you described. For example, the CWnd member function GetSafeHwnd() tests if 'this' is NULL, and returns 0 in that case. That's a cute little hack which saves you some typing when it comes to testing whether a window pointer is valid, but again, it is actually non-standard C++.
- void main() is also wrong - by the standard, main() must return int.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|