LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Predict the Output · Question 15

Static polymorphism with CRTP Answer, explanation & discussion

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

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

main.cpp
#include <iostream>

template <typename D>
struct Shape {
    double area() const { return static_cast<const D*>(this)->area_impl(); }
    double twice() const { return 2 * area(); }
};
struct Sq : Shape<Sq> { double s; explicit Sq(double x) : s(x) {} double area_impl() const { return s * s; } };
struct Rc : Shape<Rc> { double w, h; Rc(double a, double b) : w(a), h(b) {} double area_impl() const { return w * h; } };

template <typename T>
double total(const Shape<T>& a, const Shape<T>& b) { return a.area() + b.area(); }

int main() {
    Sq a(3), b(4);
    Rc r(2, 5);
    std::cout << total(a, b) << ' ' << r.twice() << ' ' << sizeof(Sq) << '\n';
    return 0;
}
  • A 25 20 8 Correct
  • B 25 20 16
  • C 7 20 8
  • D 25 10 8
Correct Answer: Option A

The base template calls the derived implementation through static_cast, resolved at compile time. There are no virtual functions, so Sq is just its double (8 bytes) – no vptr.

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