Quiz 6 — Inheritance¶
Ten questions on "is-a", construction order in a hierarchy, and the traps of the mechanism — name hiding, private inheritance and the diamond.
Attempt all of them closed-book, then mark yourself against the answers.
Concepts: is-a vs has-a · base and derived · access specifiers in inheritance ·
construction order · name hiding · the diamond · protected.
Q1. (MCQ) For class Derived : Base, what is the accessibility of Base's public
members to outside code?
- A. public
- B. private
- C. protected
- D. unchanged
Q2. (true/false) A derived class can directly access the private members of its base class.
Q3. (multiple-select) Which of these are genuine "is-a" relationships? Select all that apply.
- A. A
Managerand anEmployee - B. A
Carand anEngine - C. A
Squareand aShape - D. A
Stackand aVector - E. A
SavingsAccountand anAccount
Q4. (predict) Write the output in order.
#include <iostream>
class Base {
public:
Base() { std::cout << "Base "; }
~Base() { std::cout << "~Base "; }
};
class Derived : public Base {
public:
Derived() { std::cout << "Derived "; }
~Derived() { std::cout << "~Derived "; }
};
int main() {
Derived d;
}
Q5. (debug) s.describe() will not compile. Explain why, then give two fixes.
struct Base {
void describe() const { }
};
struct Square : Base {
void describe(int sides) const { }
};
int main() {
Square s;
s.describe();
}
Q6. (analysis) A Router inherits from both Networked and Powered, which each
inherit from Device. Why does r.id = 1; fail to compile, and what feature shares one
base?
Q7. (predict) Does main compile? Explain the difference from : public Engine.
#include <iostream>
class Engine {
public:
void start() const { std::cout << "started\n"; }
};
class Car : Engine { // note: no access specifier
public:
Car() { start(); }
};
int main() {
Car c;
c.start(); // ?
}
Q8. (short answer) What does protected access mean, and why is choosing it a
decision rather than a default?
Q9. (design) Design a small vehicle hierarchy for cars, vans and motorbikes that shares the registration plate and daily rate. State what is shared and one thing that must not go in the base, with a one-sentence reason.
Q10. (analysis) Give one case where inheriting to reuse code is the wrong choice, and name the relationship you would use instead.
Scoring: mark yourself with the answers, then read the self-assessment guide.