I don't really know if this is a dumb question or not but how would you create an instance of an object when the use wants you to. For example, lets say I make an address book that stores various information about contacts. I have a class named contact. Now when the user wants to add a new contact and when he enters the contacts name, then I want the object with the class contact to be created. The objects name should be the name of the contact the user entered. How would I do that? I hope I made the question clear....
Your class named Contact should have a constructor with the information you want it to hold, i.e. name, address, etc. You would maintain a list of contacts in an array, and when the user asks to add a contact, you can reallocate the array to add a new space, then call the constructor for the pointer with the arguments, like so:
[HIGHLIGHT="C++"]
class AddressBook
{
private:
Contact **contactList;
unsigned int numberOfContacts;
public:
//this is the constructor for your address book, which maintains a
//list of your contacts. Constructors and destructors would go here.
///////////////////////////////////
//this is the function that you wanted:
//the actual format of the arguments depends on how you have
//your contacts defined, i.e. what your Contact class
//contains.
bool addNewContact(char *name,char *address)
{
++numberOfContacts;
Contact **temp = (Contact **)realloc(contactList,numberOfContacts*sizeof(Con tact *));
//this check is only for dummy-proofing
if(temp == NULL)
return false; //this means that we're out of memory.
else
contactList = temp;
//now that we've added a new space, we need to copy the info.
contactList[numberOfContacts - 1] = new Contact(name,address);
//creation of new contact successful.
return true;
}
};
[/HIGHLIGHT]
In your program, you need to declare a variable of type AddressBook. When the user wants to create a new contact...
[HIGHLIGHT="C++"]
AddressBook *addrbk = new AddressBook();
//get user input...
//now user wants to create a new contact.
//get the appropriate information, i.e. name, address, etc....
//and now add the new contact.
addrbk->addNewContact(name,address);
[/HIGHLIGHT]
The code I provided for AddressBook is the bare minimum to illustrate my example. Feel free to copy it, but make sure you code constructors, destructors, etc. If you want a somewhat more convoluted (but still relatively easy) method of doing this without classes, just let me know.
Last edited by dargueta; 01-22-2008 at 08:30 PM. Reason: Clarified a point
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks