TryBugHunt
cppType errorMedium

Object slicing in polymorphic base class pass-by-value

BugFind the bug and fix the code

What it should do

Invoke polymorphic describe method and return shape string. Example: renderShapeDescription(true) -> "Circle"

What happens instead

Derived class object sliced to Base, returning "Generic" instead of "Circle"

#include <iostream>
#include <string>

class Shape {
public:
    virtual std::string describe() const { return "Generic"; }
};

class Circle : public Shape {
public:
    std::string describe() const override { return "Circle"; }
};

// Passing Shape by value slices the Circle object
std::string getShapeInfo(Shape s) {
    return s.describe();
}

std::string renderShapeDescription(bool isCircle) {
    if (isCircle) {
        Circle c;
        return getShapeInfo(c);
    }
    Shape s;
    return getShapeInfo(s);
}

int main() {
    std::cout << renderShapeDescription(true) << std::endl;
    return 0;
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the type errors pattern

Integer division, signed and unsigned mix-ups, and implicit conversions that change the value.

What you'll practise

A medium C++ debugging exercise about type errors: integer division, signed and unsigned mix-ups, and implicit conversions that change the value.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

What went wrong: Passing a derived object by value to a function expecting a base class copies only the base portion of the object. This phenomenon, called object slicing, strips the derived class vtable and members.

The fix: Pass the polymorphic object by reference (const Shape& s) or pointer.

Remember: Always pass polymorphic C++ classes by reference or pointer to preserve virtual dispatch.

The pattern behind it: type errors.

More type errors to practise

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/976e25f1-e716-4328-9cd4-b96a95cd523e" title="Debugging challenge: Object slicing in polymorphic base class pass-by-value" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/976e25f1-e716-4328-9cd4-b96a95cd523e">TryBugHunt</a></p>