LearnFrenzy
Sign in Take a free test

Smart Pointers · Predict the Output · Question 10

dynamic_pointer_cast on shared_ptr Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <memory>

struct Shape { virtual ~Shape() = default; };
struct Circle : Shape { double r = 2; };
struct Square : Shape {};

int main() {
    std::shared_ptr<Shape> s = std::make_shared<Circle>();
    auto c = std::dynamic_pointer_cast<Circle>(s);
    auto q = std::dynamic_pointer_cast<Square>(s);
    std::cout << (c != nullptr) << (q != nullptr) << ' ' << c->r << ' ' << s.use_count() << '\n';
    return 0;
}
  • A 10 2 2 Correct
  • B 11 2 3
  • C 10 2 1
  • D 10 2 3
Correct Answer: Option A

A successful cast returns a shared_ptr that shares ownership (count 2); a failed cast returns an empty one that owns nothing.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links