LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 10

Private inheritance with selected members re-exposed Answer, explanation & discussion

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

What is the output of the following C++ program?

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

class Queue : private std::string {
public:
    using std::string::size;
    using std::string::empty;
    void push(char c) { push_back(c); }
    char pop() { char c = front(); erase(0, 1); return c; }
};

int main() {
    Queue q;
    for (char c : {'a', 'b', 'c'}) q.push(c);
    char first = q.pop();
    std::cout << first << ' ' << q.size() << ' ' << q.empty() << '\n';
    return 0;
}
  • A a 2 0 Correct
  • B c 2 0
  • C a 3 0
  • D Compilation error
Correct Answer: Option A

Queue reuses std::string's storage privately and exposes only push, pop, size and empty. pop removes from the front: first in, first out.

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