CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List
C++ Code Walkthrough #71

Slicing: Copying a Derived Object Into a Base

mediumInheritance

📄 Code

Read carefully — what does this print?
1#include <iostream>
2#include <string>
3using namespace std;
4 
5class Shape {
6public:
7 virtual string kind() const { return "shape"; }
8 virtual ~Shape() {}
9};
10 
11class Square : public Shape {
12public:
13 string kind() const override { return "square"; }
14};
15 
16void byValue(Shape s) {
17 cout << s.kind() << endl;
18}
19 
20void byRef(const Shape& s) {
21 cout << s.kind() << endl;
22}
23 
24int 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}

🎯 Your Answer