← Back to Question List
C++ Code Walkthrough #81
Three Files: A Virtual Call Across Files
📄 Code
Read carefully — what does this print?1// ===== Shape.h =====2#ifndef SHAPE_H3#define SHAPE_H4#include <iostream>5#include <string>67class 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};1718#endif1920// ===== Rect.h =====21#ifndef RECT_H22#define RECT_H23#include "Shape.h"2425class 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};3233#endif3435// ===== main.cpp =====36#include <iostream>37#include "Rect.h"38using namespace std;3940int 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}