LearnFrenzy
Sign in Take a free test

Abstract Classes and Interfaces · Predict the Output · Question 8

Shared code in an abstract base calling pure virtuals Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

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

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

class Exam {
public:
    std::string result(int marks) const { return marks >= pass_mark() ? "pass:" + grade(marks) : "fail"; }
    virtual ~Exam() = default;
protected:
    virtual int pass_mark() const = 0;
    virtual std::string grade(int marks) const = 0;
};

class School : public Exam {
    int pass_mark() const override { return 33; }
    std::string grade(int m) const override { return m >= 75 ? "A" : "B"; }
};
class University : public Exam {
    int pass_mark() const override { return 40; }
    std::string grade(int m) const override { return m >= 60 ? "First" : "Second"; }
};

int main() {
    School s;
    University u;
    std::cout << s.result(35) << ' ' << u.result(35) << ' ' << s.result(80) << ' ' << u.result(65) << '\n';
    return 0;
}
  • A pass:B fail pass:A pass:First Correct
  • B pass:B pass:Second pass:A pass:First
  • C fail fail pass:A pass:First
  • D pass:B fail pass:A pass:Second
Correct Answer: Option A

result() is shared code in the abstract class; it calls the protected pure virtual hooks of whichever exam it is.

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