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

virtual Decides Which Function Runs

mediumInheritance

📄 Code

Read carefully — what does this print?
1#include <iostream>
2using namespace std;
3 
4class Shape {
5public:
6 virtual void draw() const { cout << "Shape::draw" << endl; }
7 void name() const { cout << "Shape::name" << endl; }
8 virtual ~Shape() {}
9};
10 
11class Circle : public Shape {
12public:
13 void draw() const override { cout << "Circle::draw" << endl; }
14 void name() const { cout << "Circle::name" << endl; }
15};
16 
17int main() {
18 Circle c;
19 Shape* p = &c;
20 Shape& r = c;
21 
22 c.draw();
23 c.name();
24 p->draw();
25 p->name();
26 r.draw();
27 r.name();
28 return 0;
29}

🎯 Your Answer