neo wrote:
> I made a console based application in vs2k5. I made a class with the
> name "A" which has one function with the name of "function" and
> has one member integer variable initialized with 99;
Just for the record: You didn't initialize with 99, you assigned 99 to it.
Non-static member variables can only be initialized in the initializer
list.
> its code is following.
>
> class A
> {
> private:
> int x;
> public:
> A( )
> {
> x = 99;
> cout<<"const of class A"<<endl;
> }
> ~A( )
> {
> cout<<"dest of class A"<<endl;
> }
> void function( )
> {
> cout<<"value of x : "<<x<<endl;
> }
> };
>
> I wrote few lines of code in main function, these are following
>
> A * ptr = &(A());
> ptr->function( );
>
> I have no idea about A(), but what I right now understand about it is,
> that it's a object created to execute its constructor and immediately
> gets destroyed when its out of its constructor and that it is allocated
> on stack.
Yes, except that it's called "automatic storage" in C++ instead of "stack".
> Now even if it is destroyed, I still have a reference (as a
> pointer) to it in form of a pointer. And now if I use that pointer to
> call its methods I can easily do so and it behaves exactly in the way
> as if it were never destroyed from the memory. Please explain this
> behavior.
The behavior is formally undefined. That means that anything can happen, and
that includes the behavior your observed.
> Note: In writing this code I also observed that when a stack based
> object is destroyed, its destruction behaves a little bit different
> than the destruction of a heap base objects (its just an observation
> and I maybe wrong about it). For example, if the above object was
> created on a heap (by using *new*), its constructor would have set its
> internal x variable to 99. I could have got a pointer to that variable
> and use it to display its value after having called a delete on A's
> pointer, but I would not get the value of x as it was when the object
> was alive. That's apparently not the case with stack based allocation
> because even after A's destruction from the stack, I continue to get
> the actually value of x as it was when the object was alive.
Again, "undefined behavior" means anything can happen. It's not really
useful to try to understand why exactly the behavor is like it is.
|