C++ Constructors and Destructors: Initializer Lists & Deep vs Shallow Copying

A Constructor is a special member function that initializes a new object upon creation. A Destructor is invoked automatically when the object goes out of scope, releasing any allocated resources.

Types of Constructors in C++

#include <iostream>

class DynamicArray {
private:
    int* buffer;
    int size;

public:
    // 1. Parameterized Constructor with Member Initializer List
    DynamicArray(int s) : size(s), buffer(new int[s]{}) {
        std::cout << "Allocated array of size: " << size << "\n";
    }

    // 2. Deep Copy Constructor
    DynamicArray(const DynamicArray& other) : size(other.size), buffer(new int[other.size]) {
        for (int i = 0; i < size; ++i) {
            buffer[i] = other.buffer[i];
        }
        std::cout << "Deep copy constructor executed!\n";
    }

    // 3. Destructor
    ~DynamicArray() {
        delete[] buffer;
        std::cout << "Destructor: Heap buffer released safely.\n";
    }
};

int main() {
    DynamicArray a1(5);
    DynamicArray a2 = a1; // Calls Deep Copy Constructor!
    return 0;
}

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. Why must Member Initializer Lists be used instead of assignments inside the constructor body?

Member initializer lists initialize fields directly upon construction, whereas assigning inside the constructor body first default-initializes the field and then overwrites it (causing double work). In addition, 'const' members and reference members CANNOT be assigned in the body; they MUST be initialized via member initializer lists.

Q2. What is the difference between a Shallow Copy and a Deep Copy?

A Shallow Copy simply copies raw pointer addresses, leaving two objects pointing to the same heap buffer; when both destructors run, a double-free crash occurs. A Deep Copy allocates a brand new heap buffer and copies the actual values, ensuring total object independence.

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

Move Constructor

High-speed resource transfer with rvalue references.

Virtual Destructors

Why polymorphic base classes require virtual destructors.

C++ RAII

Tying constructors and destructors to system resources.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!