Jump to content
YOUR-AD-HERE
HOSTING
TOOLS

Locked [tutorial]BUILDING A STACK CLASS


Breaker

Recommended Posts

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?

 

type of data

some storage

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:

  • init
  • push
  • pop
  • isEmpty
  • count
  • 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.

 

This is the hidden content, please

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.

 

This is the hidden content, please

 

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

 

This is the hidden content, please

 

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.

Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.