views:

182

answers:

1

Q1. What happens first- memory allocation or constructor call for the below written statement ?

int *ptr = new int();

Q2. What is the difference between following three approaches?

  1. If an object is destroyed with DELETE operator. Will destructor be called?
  2. If a destructor is called explicitly (e.g. a1.~A()) to destroy the object?
  3. Neither explicit destructor call is made nor DELETE operator is used to destroy the object but object goes out of scope.

What would be the behavior if the destructor is private or protected?

+2  A: 

OK, well I've given your questions a somewhat meaningful title, so I'll try to answer them as well. (Though you really should put multiple questions in multiple postings).

Q1. The allocation happens first. This is clearly the case because the object doesn't exist until it is allocated. Only then can the constructor run and give the object a value.

Q2.

1. If an object is destroyed with DELETE operator. Will destructor be called?

Yes.

2. If a destructor is called explicitly (e.g. a1.~A()) to destroy the object?

There is no real question here.

3. Neither explicit destructor call is made nor DELETE operator is used to destroy the object but object goes out of scope.

This question is ambiguous. The delete aspect of it implies the object was allocated on the heap, in which case it never goes out of scope... But the pointer to the object can go out of scope. If this is what you are talking about, then you have a memory leak.

However, if you are talking about a stack allocated object, then its destructor will be called when it goes out of scope.

Evan Teran