Shallow Copy vs. Deep Copy

Hard Object Lifecycle (Constructors & Destructors) PRO
🔒 Login to Unlock

Problem Statement

Create a `DeepData` class holding a dynamically allocated `int* val`. Write a parameterized constructor that sets `val = new int(v)`. Write a deep copy constructor that allocates a new int (`val = new int(*other.val)`) and prints ‘Deep copy’. Read an integer, instantiate obj1, copy it to obj2, and print `*obj2.val`.

Input Format

A single integer.

Output Format

Print 'Deep copy' followed by the value on a new line.

Constraints

Ensure destructor `delete val;` is implemented to prevent memory leaks.

Sample Input

45

Sample Output

Deep copy
45

Explanation

A deep copy ensures that dynamically allocated memory isn't shared between the original and the copied object, preventing double-free crashes.

Starter Code

#include <iostream>

class DeepData {
public:
    int* val;
    // Write constructor, deep copy constructor, and destructor
};

int main() {
    int v;
    if (std::cin >> v) {
        // Create obj1, deep copy to obj2, and print value
    }
    return 0;
}

Limits

  • Time Limit: 1s
  • Memory Limit: 256MB

Embedded C Programming

Updated: March 15, 2026
Intermediate

Embedded systems rely on efficient low-level programming to interact directly with hardware. In this course, you will learn how to write practical Embedded C programs used in real microcontroller-based systems. Rather than focusing only on theory, this course follows a practice-driven approach. Each lesson includes hands-on coding exercises that simulate real firmware development tasks used