<en******@gmail.comwrote in message
news:11*********************@h48g2000cwc.googlegro ups.com...
: Hi all,
: How does this work?
:
: class a{
: public:
: int geta(){
: return 2;
: }
: };
:
:
: int main(){
: a *ptr = 0;
: cout<<"Value :"<<ptr->geta();
: }
:
: this prints
: Value: 100
:
: I expected a runtime error. but this worked just fine. How?
"worked just fine" ?? I assume there is a typo in your
post then (2 vs 100).
Anyway:
- The C++ standard does not require any checks
for NULL or invalid pointers during dereferencing.
What is specified in that case is "undefined behavior"
(i.e. anything could happen).
However, some C++ platfomrs may offer the possibility
to have automated runtime checks for such errors.
- In the above example, the executed code does not
actually need to access the *ptr object to execute
function geta() -- because no data member is accessed,
and geta() is *not* declared as virtual. So although
the behavior of the code is formally undefined, it
will just happen to run without error on must C++ platforms.
hth --Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <
http://www.brainbench.com