Here’s List.h
#ifndef LIST_H
#define LIST_H
class List {
public:
List(); // Constructor
~List(); // Destructor
void addItem(int item); // Add integer item
void deleteItem(int loc); // Delete item
private:
int *ptr = nullptr;
int size = 0; // Pointer and its size
};
#endif
Here’s the List.cpp
#include "List.h"
#include <stdexcept>
List::List() {
// The constructor initializes size to 0 and ptr to nullptr
}
void List::addItem(int item) {
int *newPtr = new int[size + 1];
for (int i = 0; i < size; i++) {
newPtr[i] = ptr[i];
}
newPtr[size] = item;
delete[] ptr;
ptr = newPtr;
size++;
}
void List::deleteItem(int loc) {
if (loc < 0 || loc >= size) {
throw std::out_of_range("Index out of range");
}
int *newPtr = new int[size - 1];
for (int i = 0; i < loc; i++) {
newPtr[i] = ptr[i];
}
for (int i = loc + 1; i < size; i++) {
newPtr[i - 1] = ptr[i];
}
delete[] ptr;
ptr = newPtr;
size--;
}
List::~List() {
delete[] ptr;
}
Are you sure the “delete[], delete” thing is not wrong? Something tells me this is a double delete on the same pointer. Also, this class could benefit if you allocated memory in chunks (have a “size” member and “allocated_size”, allocate e.g. 1024 bytes more when when “size” >= “allocated_size” and vice versa when freeing memory).
Thank you very much for your attention. The first delete [] ptr is to delete array elements. The second one is not necessarry and we delete ptr. Yout are right about “size” and “allocated_size”. However, I wanted to show people the use of pointers and I did not care about efficiency. It will be more beneficial if we use chunks.
Thank you very much…