chevron_left chevron_right
Login Register invert_colors photo_library


Stay updated and chat with others! - Join the Discord!
Thread Rating:
  • 0 Vote(s) - 0 Average


Tutorial [C++] Building a stack class filter_list
Author
Message
[C++] Building a stack class #1
Alright, if you havn't already done so, go read the thread on creating your first stack (in C) here as I won't be explaining some of the basic concepts in this thread.

Another note: this one will not be as spoonfed as the last one, I assume that you understood most of it, I will, however go into some of the concepts again as things will be a touch different.

Let's get started. What are we going to need to make this class?

  1. type of data
  2. some storage
  3. methods to manage the stack

Pretty much the same as in C. lets break this down one by one.

1. type of data
For this class, we will also be using ints, I will /probably/ write a tutorial on how to make template classes, as well as one explaining how to make one that uses multiple POD types.

2. some storage
Since we are using a class, everything can be embodied into the class instead of a struct (note to experienced programmers: although classes use structs to store member data anyways)
We will use an array again to store them (fixed size), you can use resizing or linked lists if you want variable stacks, but that defeats the point (congrats, you made a vector)

3. methods to manage the stack
We will need pretty much the same methods as the C stack (init, push, pop, destroy) but we can add a few. Here is the full list:
  1. init
  2. push
  3. pop
  4. isEmpty
  5. count
  6. destroy

The new ones:
isEmpty will be a boolean that tells the user if the stack has zero elements in it (useful for removing unused items or backwards sorting)
count will just return the number of elements in the stack.

Okay, so let's write the header for our class incorporating points 2 and 3.

Code:
class myStack
{
private:
     int *data;
     int sp; //short for stack pointer
public:
     myStack(int); //the same as init, takes 1 argument: the size of the stack
     void push(int);
     int pop();
     bool isEmpty();
     int count();
     ~myStack(); //the same as destroy, but is called automatically
};

NOTE: I assume you have a basic understanding of how c++ classes work. If you do not, google "learn C++ the hard way"

Now we can get on to our code file. This will be mostly the same as the C file, so I won't spoonfeed it all to you.

Code:
#include "myStack.h"

myStack::myStack(int size)
{
     assert(size > 1); //don't create a class, the programmer is an idiot.
     data = new int[size]; //in C++ we don't need to sizeof, since new does all that for us
     sp = 0;
}

myStack::~myStack() //yes, I know it is out of order. personal preference
{
     //remember, we never call ~myStack, it happens on its own
     delete data; //delete works similar to free.
}

void myStack::push(int input)
{
     data[sp++] = input;
     /* if you don't understand this, use this one instead
      * int sp_tmp = sp;
      * data[sp_tmp] = input;
      * ++sp; //update the pointer
      */
}

int myStack::pop()
{
     return data[--sp];
     /* or
      * int sp_tmp = sp - 1; //dont forget the -1
      * int data_tmp = data[sp];
      * --sp;
      * return data_tmp;
      */
}

bool myStack::isEmpty()
{
     return (sp == 0);
     /* or
      * if (sp == 0)
      *       return true;
      *  return false;
      */
}

int myStack::count()
{
     return sp; //don't get in the habbit of this, it WILL not work on real stacks, but this is C++
}

Now, that is a considerable bit less code than the C variant, but EVERYTHING is the same. Usage is a little different.

Code:
#include "myStack.h"

int main()
{
     myStack sample_stack(5); //create a stack that can hold 5 elements
     int catch;

     sample_stack.push(4);
     sample_stack.push(3);
     sample_stack.push(2);
     sample_stack.push(1);

     while (! sample_stack.isEmpty())
          catch = sample_stack.pop();

     //note, we dont need to call ~myStack

     return 0;
}

This seems REALLY simple, so I won't bother with a poll here. I personally like the C version better, but it can EASILY be adapted to a class.

If you need help understanding this, feel free to ask questions.

Reply

RE: [C++] Building a stack class #2
Code:
~myStack(); //the same as destroy, but is called automatically

This is only partially true, and only true in the case that the object was created on the stack, otherwise it is not called automatically, you need to invoke it with the 'delete' keyword, or you'll have memory leaks.

Reply

RE: [C++] Building a stack class #3
That is correct, but once again I assumed the user is not a complete fucking moron. I don't see the need to write that, fills it with unnecessary text.

Reply

RE: [C++] Building a stack class #4
(12-31-2014, 02:14 AM)phyrrus9 Wrote: That is correct, but once again I assumed the user is not a complete fucking moron. I don't see the need to write that, fills it with unnecessary text.

Don't see the need to write what? You are responsible for error handling for encapsulated functionality within the class, not the caller. Bugs within external code might still pass 0 as an argument even if the programmer never intended, but the real problem is that the errors don't stop at his code, you allow them to proceed with execution within your own class, which is detrimental to all design principles I know of. Writing something like that which steers away from an exception being thrown is just as bad if not worse than a programmer passing invalid values to your class and utilizing your class to create undefined behavior that you don't disallow in the first place... The guarantee of a constructor is to leave the object in a valid state. If it can't do that, then you shouldn't be allowing a user to continue using the object. This is the reason why even parameterless constructors which are user defined will typically initialize pointer members to NULL or 0.

Reply

RE: [C++] Building a stack class #5
(12-31-2014, 02:31 AM)0xDEAD10CC Wrote: Don't see the need to write what? You are responsible for error handling for encapsulated functionality within the class, not the caller. Bugs within external code might still pass 0 as an argument even if the programmer never intended, but the real problem is that the errors don't stop at his code, you allow them to proceed with execution within your own class, which is detrimental to all design principles I know of.

Give me a moment to add a snippet (I personally dislike exceptions).

Reply

RE: [C++] Building a stack class #6
Alright.. I'll await to see the snippet. Also, to mention, C++ has stdConfusedtack, which is a templated type, and a few others with similar functionality including std::deque..

Reply

RE: [C++] Building a stack class #7
(12-31-2014, 03:17 AM)0xDEAD10CC Wrote: Alright.. I'll await to see the snippet. Also, to mention, C++ has stdConfusedtack, which is a templated type, and a few others with similar functionality including std::deque..

This is true as well, but the purpose is to understand how to make one, not how to use them. Some people exist (like myself) that would much rather create their own types (when possible) to keep in tune on how things work though it is simply a matter of personal preference.

As far as this thread goes, unless you see mistakes in the code or wording, please refrain from unwanted criticism or multiple methods. If you wish to bring up these issues you are free to create your own thread about that, and I encourage it.

Reply

RE: [C++] Building a stack class #8
Unwanted criticism? If you didn't expect some feedback then why do you post these threads? There are clearly some mistakes or at least some misconceptions here, I feel it's appropriate to state them if you intend on people learning from this, otherwise they are not going to be learning *much* because some of the information posted is not accurate.

Create a generic-like stack type in C next Smile.

edit: 2 days have passed, I suppose this snippet will never be posted lol.

Reply






Users browsing this thread: 1 Guest(s)