LearnFrenzy
Sign in Take a free test

Abstract Classes and Interfaces · Predict the Output · Question 19

Passing concrete objects to an abstract reference parameter Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 19 Back to Exercise

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

main.cpp
#include <iostream>

struct Sensor { virtual double read() const = 0; virtual ~Sensor() = default; };
struct Temp     : Sensor { double read() const override { return 36.5; } };
struct Humidity : Sensor { double read() const override { return 62; } };

double average(const Sensor& a, const Sensor& b) { return (a.read() + b.read()) / 2; }

int main() {
    Temp t;
    Humidity h;
    std::cout << average(t, h) << ' ' << average(t, t) << '\n';
    return 0;
}
  • A 49.25 36.5 Correct
  • B 49 36
  • C 98.5 73
  • D 49.25 49.25
Correct Answer: Option A

References to the abstract Sensor bind to any concrete sensor and dispatch to its read().

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