LearnFrenzy
Sign in Take a free test

OOPS Concepts · OOPS Programs · Question 8

A bounded Stack class with encapsulation in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Implement a Stack class with a fixed capacity on top of a private std::vector, offering push, pop, top, size and empty; push must report overflow and pop must report underflow.

Solution
main.cpp
#include <iostream>
#include <optional>
#include <vector>

class Stack {
    std::vector<int> items_;
    std::size_t capacity_;
public:
    explicit Stack(std::size_t cap) : capacity_(cap) { items_.reserve(cap); }
    bool push(int x) {
        if (items_.size() == capacity_) return false;
        items_.push_back(x);
        return true;
    }
    std::optional<int> pop() {
        if (items_.empty()) return std::nullopt;
        int x = items_.back();
        items_.pop_back();
        return x;
    }
    std::size_t size() const { return items_.size(); }
    bool empty() const { return items_.empty(); }
};

int main() {
    Stack s(3);
    for (int v : {10, 20, 30, 40})
        std::cout << "push " << v << (s.push(v) ? " ok\n" : " overflow\n");
    while (auto v = s.pop()) std::cout << "pop " << *v << '\n';
    std::cout << "pop " << (s.pop() ? "value" : "underflow") << ", size " << s.size() << '\n';
    return 0;
}

Output Verified by compiling and running

push 10 ok
push 20 ok
push 30 ok
push 40 overflow
pop 30
pop 20
pop 10
pop underflow, size 0

Callers cannot reach the vector, so the stack can only be used last-in-first-out and can never exceed its capacity. std::optional expresses "maybe a value" for pop.

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