May 27, 2015 at 11:47am UTC
In Below program do you see any error or scope of improving the design?
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;
#define MIN(x, y) (x.size() < y.size() ? x.size() : y.size())
template<class T>
class NamedStack
{
public:
typedef unsigned int SizeType;
NamedStack(string str);
NamedStack(const NamedStack<T>& orig);
~NamedStack();
NamedStack& operator=(const NamedStack<T>& rhs);
bool operator<(const NamedStack<T>& rhs);
T Pop();
void Push(T value);
int Size();
const char* Name();
protected:
T find_it();
T* data;
private:
SizeType dataSize;
string name;
};
template<class T>
NamedStack<T>::NamedStack(string str)
{
// initialize data
data = NULL;
dataSize = 0;
name = str;
}
template<class T>
NamedStack<T>::NamedStack(const NamedStack<T>& orig)
{
data = new T[orig.dataSize];
for (int i=0; i<orig.DataSize; i++)
data[i] = orig.data[i];
name = orig.name;
dataSize = orig.dataSize;
}
template<class T>
NamedStack<T>::~NamedStack()
{
delete data;
dataSize = 0;
name = "";
}
template<class T>
NamedStack<T>& NamedStack<T>::operator=(const NamedStack<T>& rhs)
{
delete data;
data = new T[rhs.dataSize];
for (int i=0; i<rhs.dataSize; i++)
data[i] = rhs.data[i];
}
template<class T>
bool NamedStack<T>::operator<(const NamedStack<T>& rhs)
{
for (int i=0; i<MIN(name, rhs.name); i++)
if (name[i] > rhs.name[i])
return false;
return true;
}
template<class T>
T NamedStack<T>::Pop()
{
T a = find_it();
T* oldData = data;
dataSize--;
data = new T[dataSize];
for (int i=0; i<dataSize; i++)
data[i] = oldData[i];
delete oldData;
return a;
}
template<class T>
void NamedStack<T>::Push(T value)
{
T* oldData = data;
data = new T[++dataSize];
for (int i=0; i<dataSize-1; i++)
data[i] = oldData[i];
delete oldData;
data[dataSize] = value;
return;
}
template<class T>
int NamedStack<T>::Size()
{
return dataSize;
}
template<class T>
const char* NamedStack<T>::Name()
{
return name.c_str();
}
template<class T>
T NamedStack<T>::find_it()
{
return data[dataSize-1];
}
May 27, 2015 at 11:55am UTC
I'd suggest code tags, indents. comments and the inclusion of main or a description so we know what the program does without having to read through many lines of unformatted, uncommented code to understand what's happening.
May 27, 2015 at 12:11pm UTC
True..also I was thinking it should have exception handling as well right..anything else?
May 27, 2015 at 12:12pm UTC
specifically from improving design...reducing lines of code?
May 27, 2015 at 2:42pm UTC
Once you've followed the first suggestion you were given, you may find more people are willing to read and comment on your code.