LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Predict the Output · Question 14

A pure virtual function that still has a body Answer, explanation & discussion

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

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

main.cpp
#include <iostream>

struct Task {
    virtual void run() const = 0;
    virtual ~Task() = default;
};
void Task::run() const { std::cout << "default setup; "; }   // allowed: pure virtual with a definition

struct Backup : Task {
    void run() const override {
        Task::run();
        std::cout << "copying files\n";
    }
};

int main() {
    Backup b;
    const Task& t = b;
    t.run();
    return 0;
}
  • A default setup; copying files Correct
  • B copying files
  • C default setup;
  • D Compilation error
Correct Answer: Option A

A pure virtual function may have a definition; the class is still abstract, but derived classes can call the shared default behaviour explicitly with Task::run().

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