you can do them both whenever. However, where I believe you are going with this is why would you use new
When there is inheritance would be the use of it. Lets say there are three classes that have Person as a parent and they are
class Childublic Person
{...}
class Teenagerublic Person
{...}
class Adultublic Person
{...}
now you can do:
Person* Peter = new Adult;
Person* Peters_Son = new Child;
Person* Peters_Sons_big_Brother = new Teenager;
Through the use of virtual functions, you could have different methods by the same name but that behave differently. Lets say Person defined a function "CanVote"
I would do:
Person Peter;
if I have enough Memory and do not wish to think about delete (Compiler calls destructor itself);
if I use object local and have many 'return' in my Funktion and do not wish to think about delete too.
I would do:
Person *Peter = new Person();
...
//Do not forget!
delete Peter;
if object Person needs more Memory (I can create it only when I really need it and delete it earlier as the compiler would do it in the first case);
if I use global object of Type Person (for example, if I have some C++ and some C - Files in my Program and need to use objects in C-Files);
if I must often delete and create one object (for example, by Errors);
allways in this case:
Person **Peter = new Person*[100];
if(Peter) {
for(int i = 0; i < 100; i++) {
Peter = new Person();
if(Peter == NULL) {
//Error - not enough Memory
break;
}
}
}
else {
//Error - not enough Memory
}
...
//Do not forget to delete it all with a loop!
for(int i = 0; i < 100; i++) {
if( Peter) {
delete Peter;
Peter = NULL; //To not delete it twice
}
}
...
if( Peter) {
delete [] Peter;
Peter = NULL; //To not delete it twice
}
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.