Quiz 8 — Abstract Classes and Interfaces¶
Ten questions on pure virtual functions, contracts, and designing an interface that callers can rely on.
Attempt all of them closed-book, then mark yourself against the answers.
Concepts: pure virtual functions · abstract types · interfaces · contracts · interface segregation · destructors in interfaces.
Q1. (MCQ) A class is abstract when it has:
- A. a
virtualfunction - B. a pure virtual function (
= 0) - C. no constructor
- D. only private members
Q2. (true/false) An abstract class may contain fully implemented member functions.
Q3. (multiple-select) Which are characteristics of a well-designed interface? Select all that apply.
- A. Only pure virtual functions, plus a virtual destructor
- B. A virtual destructor
- C. Data members for shared state
- D. A documented contract for each operation
Q4. (predict) Which line fails to compile, and why?
#include <iostream>
#include <string>
class Report {
public:
virtual std::string title() const = 0;
virtual void render() const { std::cout << title() << '\n'; }
};
class Summary : public Report {
public:
std::string title() const override { return "Summary"; }
};
int main() {
Report r; // line A
Summary s;
s.render(); // line B
}
Q5. (debug) Fix the program above with the smallest change that still gives a
reusable Report interface.
Q6. (predict) Write the output.
#include <iostream>
#include <memory>
#include <vector>
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0;
};
class Square : public Shape {
public:
explicit Square(double s) : s_(s) {}
double area() const override { return s_ * s_; }
private:
double s_;
};
class Rect : public Shape {
public:
Rect(double w, double h) : w_(w), h_(h) {}
double area() const override { return w_ * h_; }
private:
double w_, h_;
};
int main() {
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Square>(3.0));
shapes.push_back(std::make_unique<Rect>(2.0, 5.0));
double total = 0.0;
for (const auto& s : shapes) total += s->area();
std::cout << total << '\n';
}
Q7. (analysis) What is a contract in the sense this module uses the word? Give
one precondition and one postcondition for a withdraw(amount) operation.
Q8. (short answer) Why can an abstract class be a function parameter's type but not a variable's type?
Q9. (design) A kiosk plays media from files, streams and playlists through four
operations: open, play, pause, stop. Give the interface's name and signatures,
and one rule about failure that every implementation must respect.
Q10. (analysis) Why should a source that can also seek() implement a second
interface rather than having seek added to the first?
Scoring: mark yourself with the answers, then read the self-assessment guide.