what does exactly it return?
is it the same like in java?
can i do this
1 2 3 4 5 6 7 8 9 10 11
class cell{
//some attributes
cell * nextCell;
};
class memory{
cell * head , * current;
memory(){ //constructer
cell c1 = new cell;
}
};
this kind of a thing gave me an error... :(
i want to create a memory out of cells....
when i put head =new cell; it worked... but i just wanna know about this.... :)
It will actually return a void pointer (void*), which can be cast to any kind of pointer, in this case, a cell pointer (cell*).
That pointer will point to a newly created object of the type specified behind the new operator (cell). That object doesn't get destroyed when the pointer variable gets out of scope, so you need to watch out you can delete it, otherwise the memory using to store that object will still be used, that's called a memory leak.
hey thanks everyone... with ur help, i did it this way... now i see that it returns a pointer.. and new key word makes it to be made on the heap..
and thnks for mentioning about 'void*' pointers.. i never knew about that kind of a thing... it will help me on my need i guess...(i even made another post for looking for a way to retreave any data type.... i guess this void * can help me...).. if u know a good place or reference to know about 'void' and 'void*' please can u tell me...?
(i already have brought sam's c++ in 24hours book and c++ reference by herbert schildt from library...)
thnks u for help again.. :)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class memory{
private:
staticconstshort MAX_OF_CELLS = 10;
cell * head;
cell * current;
cell * alternate;
public:
// constructer
memory(){
head = new cell;
alternate = head;
for(int i=2;i<=MAX_OF_CELLS;i++){
current = new cell;
alternate->link = current;
alternate = current;
}
}
};
and new key word makes it to be made on the heap..
Technically, new allocates on the free store, while malloc() allocates on the heap. Although many people - even Stroustrup - use the term interchangeably, it has been pointed out that they're not necessarily the same. If you're interested, take a look at http://www.gotw.ca/gotw/009.htm
As a reminder, in C++ you need to deallocate anything allocated by new using the delete keyword. There's no automatic garbage collection.
The use of void* is considered evil, just as a warning. void* effectively bypasses all the compiler's type checking and can generate millions of runtime errors if abused. We have templates that do not replace void*, but do not bypass the type checking and provide most of the functionality.