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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Simple Question 1

Status
Not open for further replies.

oconv

Programmer
Jan 17, 2002
25
ZA
Here's a real easy one :

class Person{
};

when will you do:

Person Peter
and when will you
Person *Peter = new Person;

Thanks
 
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 Child:public Person
{...}

class Teenager:public Person
{...}

class Adult:public 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"

//in person.h
virtual bool CanVote(){return false;}

//in adult.h
virtual bool CanVote(){return true;}

then in your program you could do

if(Peter->CanVote())
{
// enter him into the draft
}

HOpe that helps

Matt
 
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
}

Person Peter[100]; //works not allways

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top