LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Predict the Output · Question 2

Calls through a reference, a pointer and a copy Answer, explanation & discussion

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

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

main.cpp
#include <iostream>

struct Coffee {
    virtual int price() const { return 100; }
    virtual ~Coffee() = default;
};
struct Latte : Coffee {
    int price() const override { return 180; }
};

int bill_ref(const Coffee& c) { return c.price(); }
int bill_val(Coffee c) { return c.price(); }

int main() {
    Latte l;
    const Coffee* p = &l;
    std::cout << bill_ref(l) << ' ' << p->price() << ' ' << bill_val(l) << '\n';
    return 0;
}
  • A 180 180 100 Correct
  • B 180 180 180
  • C 100 180 100
  • D 100 100 100
Correct Answer: Option A

References and pointers keep the dynamic type; passing by value slices the Latte into a plain Coffee.

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