LearnFrenzy
Sign in Take a free test

Abstract Classes and Interfaces · Predict the Output · Question 15

An abstract base counting live objects Answer, explanation & discussion

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

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

main.cpp
#include <iostream>
#include <memory>

class Widget {
    static inline int alive_ = 0;
public:
    Widget() { ++alive_; }
    virtual ~Widget() { --alive_; }
    virtual const char* kind() const = 0;
    static int alive() { return alive_; }
};
struct Label : Widget { const char* kind() const override { return "label"; } };
struct Input : Widget { const char* kind() const override { return "input"; } };

int main() {
    auto a = std::make_unique<Label>();
    {
        Input i;
        auto b = std::make_unique<Input>();
        std::cout << Widget::alive() << ' ';
    }
    std::cout << Widget::alive() << ' ' << a->kind() << '\n';
    return 0;
}
  • A 3 1 label Correct
  • B 3 3 label
  • C 2 1 label
  • D 1 1 label
Correct Answer: Option A

The abstract base's constructor and destructor run for every concrete object; two of them die at the closing brace.

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