LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Predict the Output · Question 3

Destructors called through a base pointer Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>

struct A { virtual ~A() { std::cout << "~A "; } };
struct B : A { ~B() override { std::cout << "~B "; } };
struct C : B { ~C() override { std::cout << "~C "; } };

int main() {
    A* p = new C;
    delete p;
    B* q = new B;
    delete q;
    std::cout << '\n';
    return 0;
}
  • A ~C ~B ~A ~B ~A Correct
  • B ~A ~A
  • C ~A ~B ~C ~A ~B
  • D ~C ~B ~A ~A
Correct Answer: Option A

Because ~A is virtual, deleting through A* starts with the most derived destructor and runs every destructor in reverse order of construction.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links