Monday, May 24, 2010

C++ question ?

What is the scope of an object off the heap ? Can I return an object pointer to main or will it go out of scope?





Like this





myclass* function()


{


myclass* p=new myclass;


return p;


}

C++ question ?
You can remember it this way: an object that has been created using new (which would, as you wrote, be stored on the heap), has to be disposed of explicitly using delete. All that goes out of scope in your code, is the variable p but it only points to the object, and the address it points to is copied to the variable that is used in the calling function to store the return value in.





So returning a pointer to a new-ly created object is perfectly acceptable. Just don't forget to delete it in the calling function (in your case, apparently, main()).
Reply:Awe man, I have no clue what you just said, but it sounded "programmery"





I'll have to read that PDF





I have no clue but I'll star


No comments:

Post a Comment