Deleting an object from an Array

I have created an array of customer's, initially empty, where a new customer can be added, and given a unique ID ( ID = number of customers + 1 ).

I want to be able to delete a customer from the array, given its ID, but not sure how to go about it :/

1
2
3
4
5
6
7
8
9
10
11
int noOfCustomers = 0;
Customer cust[1];
int cID;

cust[noOfCustomers].addNewCustomer();
noOfCustomers++;

cout << "Enter Customer ID to delete > ";
cin >> cID;



Am I going to need a new method in my Customer class (deleteCustomer(int ID))?

and then cust[ID-1].deleteCustomer();

What would be in deleteCustomer()? :S

Thank you for your help
Probably just zero the data.

You'd have to do the array re-sizing outside of the class in this function:

1
2
3
4
5
6
7
8
9
10
11
12
13
int noOfCustomers = 0;
Customer cust[1];
int cID;

cust[noOfCustomers++].addNewCustomer(); // Note, we can combine lines 5-6 above

cout << "Enter Customer ID to delete > ";
cin >> cID;

for (int i = cID; i+1 < noOfCustomers; ++i)
    cust[i] = cust[i+1]; // Shift everything down

cust[noOfCustomers--].deleteCustomer(); // Delete the last customer by zeroing the data 
Last edited on
Stewbond wrote:
Note, we can combine lines 5-6 above
Yes, we can, we shouldn't, but we can. A very bad pitfall though...

aaand
cust[noOfCustomers--].deleteCustomer();
we stepped in our carefully planned pittfall: noOfCustomers is out of bounds!

Writing it that irritating way would be:
cust[--noOfCustomers].deleteCustomer();


But really don't save lines at the wrong end:
1
2
3
4
5
6
7
cust[noOfCustomers].addNewCustomer();
noOfCustomers++;

....

--noOfCustomers;
cust[noOfCustomers].deleteCustomer();
is fine!
I have tried deleting customers that way but they're not really deleted :S

i.e. If i call my showPersonDetails() method, it still shows the 'deleted' customer but with '0' values :/

Will I need a destructor? ~Customer()?

If i call my showPersonDetails() method, it still shows the 'deleted' customer but with '0' values
Then your showPersonDetails() is wrong.

You need a loop that ends before noOfCustomers (i < noOfCustomers) is reached! You shall not see anything beyond that point
use a variable to save the first empty element in your array.

if you want to add a new element you just pass the id, add your element and increase the id.

if you want to delete something, you decrease the id. the element is not really deleted that way, but it gets overwritten the next time you add something.

Thanks for your replies coder777 and Darkmaster!

Apparently we're supposed to use pointers to a Customer and delete the pointers but I'm not entirely sure how this works.

I have tried:

Customer* cust[1];

creating a pointer to Customers, but then my calls to:

cust[i].anything()

have the error:

"Expression must have a class type"

:\
Topic archived. No new replies allowed.