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

Three Files: A Virtual Call Across Files

hardInheritance

📄 Code

Read carefully — what does this print?
1// ===== Shape.h =====
2#ifndef SHAPE_H
3#define SHAPE_H
4#include <iostream>
5#include <string>
6 
7class Shape {
8 std::string m_name;
9public:
10 Shape(const std::string& name) : m_name(name) {}
11 virtual ~Shape() {}
12 virtual double area() const { return 0; }
13 void describe() const {
14 std::cout << m_name << " area " << area() << std::endl;
15 }
16};
17 
18#endif
19 
20// ===== Rect.h =====
21#ifndef RECT_H
22#define RECT_H
23#include "Shape.h"
24 
25class Rect : public Shape {
26 double m_w;
27 double m_h;
28public:
29 Rect(double w, double h) : Shape("rect"), m_w(w), m_h(h) {}
30 double area() const override { return m_w * m_h; }
31};
32 
33#endif
34 
35// ===== main.cpp =====
36#include <iostream>
37#include "Rect.h"
38using namespace std;
39 
40int main() {
41 Rect r(3, 4);
42 Shape s("plain");
43 r.describe();
44 s.describe();
45 Shape* p = &r;
46 p->describe();
47 cout << p->Shape::area() << endl;
48 return 0;
49}

🎯 Your Answer