LearnFrenzy
Sign in Take a free test

Abstract Classes and Interfaces · Predict the Output · Question 20

Initialising abstract base data through its constructor Answer, explanation & discussion

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

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

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

class Course {
protected:
    std::string title_;
    int hours_;
    Course(std::string t, int h) : title_(std::move(t)), hours_(h) {}   // protected: for derived classes only
public:
    virtual int fee() const = 0;
    std::string summary() const { return title_ + "/" + std::to_string(hours_) + "h/" + std::to_string(fee()); }
    virtual ~Course() = default;
};

struct Online : Course {
    Online(std::string t, int h) : Course(std::move(t), h) {}
    int fee() const override { return hours_ * 100; }
};
struct Classroom : Course {
    Classroom(std::string t, int h) : Course(std::move(t), h) {}
    int fee() const override { return hours_ * 250 + 1000; }
};

int main() {
    Online o("C++", 40);
    Classroom c("DSA", 30);
    std::cout << o.summary() << ' ' << c.summary() << '\n';
    return 0;
}
  • A C++/40h/4000 DSA/30h/8500 Correct
  • B C++/40h/4000 DSA/30h/7500
  • C C++/40h/0 DSA/30h/0
  • D Compilation error
Correct Answer: Option A

The abstract class's protected constructor initialises the shared data; summary() calls the pure virtual fee() of the real object: 40 × 100 and 30 × 250 + 1000.

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