Re: Why use new?
On 26 mar, 19:04, saneman <asdf...@asd.com> wrote:
In the below code I make 2 instances of the class Bob. The first
instance does not use new (automatic allocation?) and the second
instance is used with new (dynamic allocation?)
#include<iostream>
class Bob {
public:
Bob(int a): n(a) {}
int getn() {
return n;
}
private:
int n;
};
int main() {
Bob b1(22);
printf("n = %d\n", b1.getn());
Bob* b2 = new Bob(88);
printf("n = %d\n", b2->getn());
return 0;
}
But when are there any reason to use new?
Lots. Most of the time, you use new because you need an
explicit lifetime for the object. You create it in some low
level function, in response to an external event, and you delete
it in some other low level function, in response to some other
external event.
Other reasons might be because you won't know the actual type
until runtime, or the object is part of a dynamic, variably
sized data structure.
And will the b2 pointer automatically be deallocated when main
returns?
Of course not. That would sort of defeat the purpose of dynamic
allocation, wouldn't it?
(Actually, in the case of main, the memory will be deallocated
when you return from the function. Not immediately, but
returning from main means terminating the program, and on
program terminiation, the memory will all be deallocated. But
in general, the purpose of using new is precisely to ensure that
the object lives until you want to explicitly terminate its
lifetime.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34