LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Predict the Output · Question 5

Virtual calls in constructors and destructors Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

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

main.cpp
#include <iostream>

struct Base {
    Base()  { who(); }
    virtual ~Base() { who(); }
    virtual void who() const { std::cout << "B"; }
};
struct Derived : Base {
    Derived()  { who(); }
    ~Derived() override { who(); }
    void who() const override { std::cout << "D"; }
};

int main() {
    { Derived d; std::cout << '|'; }
    std::cout << '\n';
    return 0;
}
  • A BD|DB Correct
  • B DD|DD
  • C BB|BB
  • D DB|BD
Correct Answer: Option A

While Base's constructor or destructor runs, the object behaves as a Base, so who() prints B there; in Derived's constructor and destructor it prints D.

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