LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Find the Error · Question 9

Error: an abstract class as a by-value parameter Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#include <iostream>

struct Plugin {
    virtual const char* name() const = 0;
    virtual ~Plugin() = default;
};
struct Exporter : Plugin {
    const char* name() const override { return "exporter"; }
};

void show(Plugin p) { std::cout << p.name() << '\n'; }

int main() {
    Exporter e;
    show(e);
    return 0;
}
  • A name must not be const
  • B An abstract class cannot be a by-value parameter type, because that would create a Plugin object; take const Plugin& instead Correct
  • C Exporter must be final
  • D show must be virtual
Correct Answer: Option B

Passing by reference also avoids slicing, which is exactly what you want for polymorphic objects.

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