Smart Pointers with Polymorphism

Medium Smart Pointers
Solve in Playground →

Problem Statement

Write a C++ program using `std::unique_ptr` with polymorphism to invoke base/derived virtual methods dynamically.

Input Format

A choice character ('D' for Dog, 'C' for Cat).

Output Format

Print animal sound via polymorphic smart pointer.

Constraints

Choice is D or C

Sample Input

D

Sample Output

Dog Barks

Explanation

Smart pointers seamlessly manage polymorphic base pointers, guaranteeing correct virtual destruction.

Starter Code

#include <iostream>
#include <memory>

class Animal {
public:
    virtual void sound() = 0;
    virtual ~Animal() {}
};

class Dog : public Animal {
public:
    void sound() override { std::cout << "Dog Barksn"; }
};

class Cat : public Animal {
public:
    void sound() override { std::cout << "Cat Meowsn"; }
};

int main() {
    char choice;
    if (std::cin >> choice) {
        // Write your polymorphic unique_ptr logic here
    }
    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