Menu
Coddy logo textTech

Recap - Dynamic Array Manager

Part of the Object Oriented Programming section of Coddy's C++ journey. Lesson 17 of 104.

challenge icon

Challenge

Easy

Let's build a DynamicArray class that manages its own memory, automatically growing when needed, just like std::vector works under the hood!

You'll create two files to organize your code:

  • DynamicArray.h: Define a DynamicArray class that manages a dynamically-sized array of integers. Your class should have:
    • Private members: a pointer to the data array, the current size (number of elements), and the capacity (allocated space)
    • A constructor that takes an initial capacity, allocates the array on the heap, and initializes size to 0
    • A destructor that frees the allocated memory and prints "DynamicArray destroyed"
    • A push(int value) method that adds an element to the array. If the array is full, it should double the capacity by allocating a new larger array, copying existing elements, and freeing the old array
    • A get(size_t index) method that returns the element at the given index
    • A getSize() method that returns the current number of elements
    • A getCapacity() method that returns the current capacity
  • main.cpp: Read an initial capacity and a count of values to add. Then read that many integer values and push each one into your DynamicArray. After adding all values, print:
    • "Size: <size>"
    • "Capacity: <capacity>"
    • "Elements: <e1> <e2> ..." (all elements separated by spaces)

The input format will be:

  • First line: initial capacity (integer)
  • Second line: number of values to add (integer)
  • Following lines: one integer value per line

When resizing, your array should double its capacity. For example, if you start with capacity 2 and push a third element, the capacity should become 4. This demonstrates the RAII principle. Your class acquires memory in the constructor and releases it in the destructor, ensuring no memory leaks.

Include your header file in main.cpp using #include "DynamicArray.h".

Try it yourself

#include <iostream>
#include "DynamicArray.h"

using namespace std;

int main() {
    // Read initial capacity
    int initialCapacity;
    cin >> initialCapacity;

    // Read number of values to add
    int numValues;
    cin >> numValues;

    // TODO: Create a DynamicArray with the initial capacity

    // TODO: Read numValues integers and push each into the array

    // TODO: Print "Size: <size>"

    // TODO: Print "Capacity: <capacity>"

    // TODO: Print "Elements: <e1> <e2> ..." (all elements separated by spaces)

    return 0;
}

All lessons in Object Oriented Programming

Practice on your own: Online C++ compiler