Implementing Prototype Pattern for Integer Vectors: Shallow vs. Deep Cloning in C++

Encapsulate a dynamic-length mathematical integer vector in C++ using pointers to manage dynamic memory. Implement both shallow and deep cloning mechanisms, then analyze their differences.

Class Structure

The IntVector class models a mathematical vector with the following core components:

  • Private members: A dynamic integer array (int* data) to store vector elements, and an integer (size) representing the vector length.
  • Public interface: Parameterized constructor, copy constructor (for shallow/deep cloning), destructor, overloaded subscript operators (const and non-const), a method to retrieve the vector size, and a method to display the vector.

Source Code and Results

1. Shallow Cloning Implementation

#include <iostream>
#include <algorithm>
using namespace std;

class IntVector {
private:
    int* data;
    int size;

public:
    // Parameterized constructor: Creates a vector of given size, initialized to 0
    IntVector(int vecSize) : size(vecSize) {
        data = new int[size];
        fill_n(data, size, 0); // Initialize all element to 0
    }

    // Shallow copy constructor
    IntVector(const IntVector& other) {
        size = other.size;
        data = other.data; // Copy pointer directly (shared memory)
    }

    // Destructor
    ~IntVector() {
        delete[] data;
    }

    // Const subscript operator: Read-only access
    int operator[](int index) const {
        return data[index];
    }

    // Non-const subscript operator: Read-write access
    int& operator[](int index) {
        return data[index];
    }

    // Get vector size
    int getSize() const {
        return size;
    }

    // Display vector elements
    void print() const {
        for (int i = 0; i < size; ++i) {
            cout << data[i];
            if (i != size - 1) {
                cout <<

Tags: C++ Prototype Pattern Shallow Cloning Deep Cloning Object-Oriented Programming

Posted on Thu, 27 Aug 2026 16:57:10 +0000 by pacmon