Back to questions
JuniorTheoryCommon
What does the program print?
#include <iostream>
struct Shape {
virtual int sides() const { return 0; }
};
struct Square : public Shape {
int sides() const override { return 4; }
};
int by_value(Shape s) { return s.sides(); }
int by_ref(const Shape& s) { return s.sides(); }
int main() { Square sq; std::cout << by_value(sq) << ' ' << by_ref(sq); }0 4
- Expecting
4 4:by_valuegets a newShapecopied from theShapepart ofsq, so the call inside it runsShape::sides. - Expecting
0 0: a reference toShapestill refers to theSquareobject itself, and a virtual call through it runsSquare::sides.
- What does the parameter of
by_valuecontain, and what happened to the rest ofsq? - How could
Shapebe written so that a call likeby_value(sq)no longer compiles?