main.cpp:
#include <iostream>
#include "array_list.h"
int main() {
array_list dynamic_list;
dynamic_list.print();
dynamic_list.append(2);
dynamic_list.append(4);
dynamic_list.print();
return 0;
}
array_list.cpp:
#include "array_list.h"
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
//class constructor
array_list::array_list() {
size = 0;
capacity = 1;
growth_factor = 2;
data = new int[capacity];
}
array_list::~array_list() {
delete[] list;
}
array_list::array_list(vector<int> initial) {
size = 0;
capacity = 1;
list = new int[capacity];
for (int x: initial) {
append(x);
}
}
int array_list::length(){
return size;
}
void array_list::resize() {
if (size > capacity) {
capacity *= growth_factor;
int *temp_list = new int[capacity];
for (int i = 0; i < size; i++){
temp_list[i] = list[i];
}
delete[] list;
list = temp_list;
}
}
void array_list::append(int n) {
if (size >= capacity) {
resize();
}
list[size] = n;
size++;
}
void array_list::print() {
{
if (size == 0) {
cout << "size is 0, empty list" << endl;
} else if (size > 0) {
cout << "[";
for (int i = 0; i < size - 1; i++) {
cout << list[i];
cout << ", ";
}
cout << list[size - 1] << "]" << endl;
}
}
}
array_list.h:
#include "math.h"
#include <iostream>
#include <iomanip>
#include <vector>
#include <stdexcept>
#include <cmath>
using namespace std;
class array_list {
private:
int size;
int growth_factor;
int capacity;
int *list;
public:
array_list();
~array_list();
array_list(vector<int>initial);
void resize();
void append(int temp);
void print();
int length();
};
#endif
I am making a custom list class in c++. I want to test it, but when I do, I get no output to the terminal. I have been looking at the code for hours, and yes I have tried with a debugger. A fresh set of eyes is nice to have when stuck in situations like these.
When I run this code, I am supposed to get the following output to the terminal: [2, 4]
But I get nothing instead. What is wrong here?
Update: I found the issue. I had reinstantiated the variables within the constructor making them local variables. This ultimately ruined the entire structure of the object.