Re: what wrong ??



"collay" <mosan1981@xxxxxxx> wrote in message
news:uvDtt0wgFHA.3868@xxxxxxxxxxxxxxxxxxxxxxx
> #include <iostream.h>
> class A
> {
> public:
> int a;
> };
>
> void main(void)
> {
> A A1;
> A* A2 = new A;
> A* A3;
> cout<<A1.a<<endl;//right (1)
> cout<<A2.a<<endl;//right (2)
> cout<<A3.a<<endl;//wrong,Unhandled exception:0xC0000005,access
> violation??
> (3)
> }
>
> what`s wrong?

Short answer, - everything is wrong.

For all three lines (1),(2),(3) compiler can do anything, - crash is just
one possibility.
Line 1 - undefined behavior, because A1.a was never initialized.
Line 2 - same undefined behavior, but the object was created on the free
store.
Line 3 - undefined behavior, the pointer A3 was never initialized.

And the moral of this story, always initialize your variables.

Gene


.



Relevant Pages


Loading