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

Virtual Destructor Through a Base Pointer With a Live Count

hardInheritance

📄 Code

Read carefully — what does this print?
1#include <iostream>
2using namespace std;
3 
4class A {
5public:
6 static int live;
7 A() { live++; cout << "A() live=" << live << endl; }
8 virtual ~A() { live--; cout << "~A() live=" << live << endl; }
9};
10int A::live = 0;
11 
12class B : public A {
13public:
14 B() { cout << "B()" << endl; }
15 ~B() { cout << "~B()" << endl; }
16};
17 
18class C : public B {
19public:
20 C() { cout << "C()" << endl; }
21 ~C() { cout << "~C()" << endl; }
22};
23 
24int main() {
25 A* p = new C;
26 B b;
27 cout << "live=" << A::live << endl;
28 delete p;
29 cout << "live=" << A::live << endl;
30 return 0;
31}

🎯 Your Answer