Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

simple question - constructors and destructors related 1

Status
Not open for further replies.

DotNetGnat

Programmer
Mar 10, 2005
5,548
IN
Guys,

let say I have a class A and I use the following two lines of code...

A a("ddd");

A* pa = new A("dsfd");

This is my understanding...The first one creates an object of class A and the second one creates an object of class A and returns a pointer reference...is that right...

when both of these objects go out of scope, does the destructor get called in both cases...or since I have used the new keyword in the second case...do I need to explicitly use delete keyword to deallocate the memory...

please shed some light on this issue...

thanks

-DNG
 
If you called new, then you need to call delete.
If you called new[], then you need delete[].



--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
thank you Salem...

So do I need to have delete in the destructor or in the same method where I have used new?? any sample code will be very helpful...

thanks

-DNG
 
// This gets created on the stack, so when it does out of scope, the destructor is called and it disappears.
A a("blah");

// This gets created on the heap, and therefore continues to take up space in memory until YOU call delete on it. Once YOU call delete, the destructor is called and the memory is freed.
A* pA = new A("blah");

Code:
int main()
{
   A a("stack");
   A* pA = new A("heap");
   ...
   delete pA;
   return 0;
}
 
thanks cpjust...exactly this is the information I was looking for...

have star...

-DNG
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top