Question

I am trying to learn and implement classes and encountered this problem of implementing nested classes. I have implemented a version of it. I wanted to ask whether you would consider it a good example for nested classes? How can we achieve the same purpose without nesting these classes?

#include<iostream>

class Stack {
    class Node {
        public:
            int data;
            Node* next;
            Node(int data, Node* next);
            ~Node();
    }* head;
    public:
        Stack();
        Stack(const Stack& s);
        void operator=(const Stack& s);
        ~Stack();
        void push(int data);
        int peek() const;
        int pop();
};
Was it helpful?

Solution

I wanted to ask whether you would consider it a good class design?

No, because you don't need linked list to implement stack, because you don't throw exceptions, because you aren't using existing solutions (such as std::stack, std::vector or std::deque), and because your class doesn't obey rule of three.

template<typename Val> class Stack{
protected:
    typedef std::vector<Val> Data;
    Data data;     
public:
    const Val& top() const{
        if (!data.size())
            throw std::underflow_error();
        return data[data.size()-1];
    }
    void push(const Val& arg){
        data.push_back(arg);
    }
    Val pop(){
        Val result = top();
        data.pop_back();
        return result;
    }
};

this problem of implementing nested classes.

For "nested classes exercise" linked list is more suitable.

How should I go about it? What should be my approach towards it?

Write as little as possible, reuse existing solutions, and keep it simple.

Are there any good books on it?

There should be books about design patterns, but it might be too early for them. I'd suggest to just keep practicing for a while, preferably using real problems you're interested in.

OTHER TIPS

I personally think nested classes can be a good design choice, but you will need to weigh out if they fit your current situation. In your specific case, it seems fine to me to implement it as a nested class. I would think it is important, that the nested class only has little functionality and is specific to the class that it is nested in.

For further discussion look in this thread: Pros and cons of using nested C++ classes and enumerations?

Hope this helps :)

edit: A different approach would be to implement it as a flat class structure and don't nest the classes. This has some advantages like the possibility for forward declarations, which can be useful for more complex structures.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top