Click to See Complete Forum and Search --> : new operator


potluck
September 17th, 2002, 12:05 AM
Hey im just a begginer at this language and im having a real difficult time. Im not sure what this means. I was asked to create like six forms which i did but now it says do this. im kinda lost please help.

You MUST create all the forms using the new operator. For example,


int main()
{
form *[5];
return 0;
}

jfaust
September 17th, 2002, 12:16 AM
form[0] = new form();
form[1] = new form();
...
form[5] = new form();


or (better) ...

for( int i = 0; i < 5; ++i )
{
form[i] = new form();
}

Jeff

Gabriel Fleseriu
September 17th, 2002, 01:02 AM
Originally posted by jfaust
form[0] = new form();
form[1] = new form();
...
form[5] = new form();


or (better) ...

for( int i = 0; i < 5; ++i )
{
form[i] = new form();
}

Jeff

That probably was a typo, but if form is a type nameform[i] = new form(); won't compile. I think you meant
const int forms = 5
form *form_[forms];
for( int i = 0; i < forms; ++i )
{
form_[i] = new form();
}

jfaust
September 17th, 2002, 10:38 AM
Right. I was attempting to keep the same "form" as the OP (pun intended). Thanks for catching that and avoiding further confusion.

Jeff

potluck
September 19th, 2002, 07:03 PM
im still in the dark.
I have a base class form and have to create osap, school, bank and apply forms. Could someone explain how i would use the new operator please.

cup
September 20th, 2002, 05:24 AM
I assume osap, school, bank and apply forms are derived from form, so you'd possibly have something like

class form
{
public:
virtual ~form() {}
};
class osap: public form {}
class school: public form {}
class bank: public form {}
class apply: public form {}

main ()
{
// To create pointers to the different forms
form* aform[4];
int i = -1;

aform[++i] = new osap;
aform[++i] = new school;
aform[++i] = new bank;
aform[++i] = new apply;
...


// When you want to delete them
for (i = 0; i < 4; i++)
delete aform[i];
}

The declaration creates pointers. Each pointer has to be assigned an instance using the new operator.

potluck
September 20th, 2002, 10:55 AM
one question , what does the virtual ~form do??

jfaust
September 20th, 2002, 11:12 AM
When you call delete on the base class object, it will call the correct derived class destructor. Any class acting as a base class should always have a virtual destructor.

Jeff

cup
September 20th, 2002, 11:13 AM
It is the destructor. When aform[i] is deleted, it calls the destructor of the derived object: not just the form destructor. The easiest way to see this is to put couts in the destructors.