← Back to Question List
C++ Code Walkthrough #71
Slicing: Copying a Derived Object Into a Base
📄 Code
Read carefully — what does this print?1#include <iostream>2#include <string>3using namespace std;45class Shape {6public:7 virtual string kind() const { return "shape"; }8 virtual ~Shape() {}9};1011class Square : public Shape {12public:13 string kind() const override { return "square"; }14};1516void byValue(Shape s) {17 cout << s.kind() << endl;18}1920void byRef(const Shape& s) {21 cout << s.kind() << endl;22}2324int main() {25 Square sq;26 Shape copy = sq;27 cout << copy.kind() << endl;28 byValue(sq);29 byRef(sq);30 Shape* p = new Square;31 cout << p->kind() << endl;32 delete p;33 return 0;34}