Lists in C++, Overloading methods? - c++

Good evening guys, I'm totally new to C++ and I've been having some troubles with it.
Now, I'm trying to make a List, after a lot of undos and corrections, I found this error that I cannot solve.
#define MAXLIST 100
template <typename T>
class List {
private:
int maxList;
int last = 0;
T* List;
public:
List();
explicit List(int tam);
bool listIsFull();
void destroyList();
List<T>() {
last = -1;
maxList = MAXLIST;
list = new T[maxList];
}
List<T>(int tam) {
last = -1;
maxList = tam;
list = new T[maxList];
}
void destroyList() {
last = -1;
}
bool listIsFull() {
if(last == MAXLIST -1)
return true;
else
return false;
}
}
Both methods destroyList() and listIsFull(), in my IDE show an error like: 'Cannot be overloaded'
And both constructors show an error like: 'Does not name a type'
What is that, that i'm doing wrong?
Thank you in advance.

The way your code appeared to me, you tried to prototype your class and then provide implementation below it, I simply added correct scope and template operators.
#define MAXLIST 100
template <typename T>
class List {
private:
int maxList;
int last = 0;
T* List;
public:
List();
explicit List(int tam);
bool listIsFull();
void destroyList();
};
template<typename T>
List<T>::List<T>() {
last = -1;
maxList = MAXLIST;
list = new T[maxList];
}
template<typename T>
List<T>::List<T>(int tam) {
last = -1;
maxList = tam;
list = new T[maxList];
}
template<typename T>
void List<T>::destroyList() {
last = -1;
}
template<typename T>
bool List<T>::listIsFull() {
if (last == MAXLIST - 1)
return true;
else
return false;
}

Related

How to build a operator== in template class

I have a assignment where I'm suppose to build template using these specifications.
ISet is a container that holds values ​​of a certain where order doesn't matter and
which does not allow duplicates (or multiples).
A dynamically allocated array of type T should be used as an internal data structure for the Set.
The Set should inherit from the ISet interface below - this must not be modified:
template <typename T>
class ISet
{
public:
virtual bool insert (T element) = 0;
virtual bool remove (T element) = 0;
virtual int size () const = 0;
};
• insert (T element): adds elements to the set and returns true provided that
the element is not already present in the quantity (in which case the element is not added and false is returned).
• remove (T element): removes elements from the set and returns true.
If the element is missing in the quantity, false returns.
• size (): returns the number of elements in the set.
In addition to the member functions, you must implement constructor, destructor, copy constructor
and assignment operator.
And so far have I come up with this code:
#pragma once
#include <string>
#include <iostream>
using namespace std;
template <class T>
class ISet
{
public:
virtual bool insert(T element) = 0;
virtual bool remove(T element) = 0;
virtual int size() const = 0;
};
#pragma once
#include "ISet.h"
template <class T>
class Set : public ISet<T>
{
public:
Set(string name);
~Set();
Set(const Set &origin);
//Set& operator=(const Set &origin);
bool insert(T element);
bool remove(T element);
int size()const;
private:
string name;
T *arr;
int cap, nrOfElement;
};
template<class T>
Set<T>::Set(string name)
{
this->name = name;
this->cap = 10;
this->nrOfElement = 0;
this->arr = new T[this->cap];
}
template<class T>
Set<T>::~Set()
{
delete[] arr;
}
template<class T>
Set<T>::Set(const Set & origin)
{
this->nrOfElement = origin.nrOfElement;
this->cap = origin.cap;
arr = new T*[cap];
for (int i = 0; i < nrOfElement; i++)
{
arr[i] = origin.arr[i];
}
}
template<class T>
bool Set<T>::insert(T element)
{
bool found = false;
if (nrOfElement == 0)
{
this->arr[0] = element;
this->nrOfElement++;
}
else
{
for (int i = 0; i < this->nrOfElement; i++)
{
if (this->arr[i] == element)
{
i = this->nrOfElement;
found = true;
}
}
if (found == false)
{
this->arr[nrOfElement++] = element;
}
}
return found;
}
template<class T>
bool Set<T>::remove(T element)
{
bool removed = false;
for (int i = 0; i < this->nrOfElement; i++)
{
if (this->arr[i] == element)
{
this->arr[i] = this->arr[nrOfElement];
nrOfElement--;
removed = true;
}
}
return removed;
}
template<class T>
int Set<T>::size() const
{
return this->nrOfElement;
}
And my problems starts when I start to test this code by adding the different data-type we are suppose to test the template against.
#include "Set.h"
#include "ISet.h"
#include "Runner.h"
int main()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
Set<string> test("test");
test.insert("lol");
cout << test.size();
test.remove("lol");
cout << test.size();
Set<Runner> test2("test");
getchar();
return 0;
}
Getting the error saying that "No operator found which takes a left-hand operand type of 'Runner'. So I have to create a operator== that handles this but don't know?
Runner class looks like this:
#pragma once
#include "Competitor.h"
#include <string>
using namespace std;
class Runner : public Competitor
{
public:
Runner();
Runner(string firstName, string lastName, int startNr);
~Runner();
void addResult(int resultTime);
int getResult() const;
string toString() const;
Runner *clone() const;
private:
int resultTime;
};
#include "Runner.h"
Runner::Runner()
{
this->resultTime = 0;
}
Runner::Runner(string firstName, string lastName, int startNr) : Competitor(firstName, lastName, startNr)
{
this->resultTime = 0;
}
Runner::~Runner()
{
}
void Runner::addResult(int resultTime)
{
this->resultTime = resultTime;
}
int Runner::getResult() const
{
return this->resultTime;
}
string Runner::toString() const
{
return (to_string(this->resultTime) + " sec");
}
Runner * Runner::clone() const
{
return new Runner(*this);
}
How do I build a operator== that will work for this?
You need to add operator== to the Runner class:
bool operator==(const Runner& other) const;

Identifier not found for this function in c++

Ok i wrote this class that counts how many leaves are there in a binary tree:
#ifndef _UTIL_BIN_TREE_H_
#define _UTIL_BIN_TREE_H_
#include"bin_treec.h"
template <class T>
class util_bin_tree
{
public:
static int n_leaf(const Bin_treec<T>& T) {
int i;
if (!T.empty())
{
if (T->spazio[i].sinistro == NULL && T->spazio[i].destro == NULL)
return 1;
else
return n_leaf(T->T->spazio[i + i].sinistro) + n_leaf(T->T->spazio[i + i].destro);
}
};
static int n_level(const Bin_treec<T>& T, int i)
{
//
};
};
#endif
this is the class that creates the binary tree:
#ifndef _Bin_treecC_H_
#define _Bin_treecC_H_
#include "Bin_tree.h"
#include "exceptions.h"
template <class T>
class Bin_treec : public Bin_tree<T, int> {
static const int NIL = -1;
public:
typedef typename Bin_tree<T, int>::value_type value_type;
typedef typename Bin_tree<T, int>::Nodo Nodo;
struct _cella {
Nodo genitore;
Nodo sinistro;
Nodo destro;
value_type valore;
};
typedef struct _cella Cella;
// costruttori e distruttori
Bin_treec();
Bin_treec(int);
~Bin_treec();
// operatori
void create();
bool empty() const;
Nodo root() const;
Nodo parent(Nodo) const;
Nodo sx(Nodo) const;
Nodo dx(Nodo) const;
bool sx_empty(Nodo) const;
bool dx_empty(Nodo) const;
//void costr(Bin_treec<T>);
void erase(Nodo);
T read(Nodo) const;
void write(Nodo, value_type);
void ins_root();
void ins_sx(Nodo);
void ins_dx(Nodo);
private:
int MAXLUNG;
Cella* spazio;
int nNodi;
Nodo inizio;
Nodo libera;
};
template <class T>
Bin_treec<T>::Bin_treec()
{
MAXLUNG = 100;
spazio = new Cella[MAXLUNG];
create();
}
template <class T>
Bin_treec<T>::Bin_treec(int nNodi) : MAXLUNG(nNodi)
{
spazio = new Cella[nNodi];
create();
}
template <class T>
Bin_treec<T>::~Bin_treec()
{
erase(inizio);
delete[] spazio;
}
template <class T>
void Bin_treec<T>::create()
{
inizio = NIL;
for (int i = 0; i < MAXLUNG; i++)
{
spazio[i].sinistro = (i + 1) % MAXLUNG;
}
libera = 0;
nNodi = 0;
}
template <class T>
bool Bin_treec<T>::empty() const
{
return(nNodi == 0);
}
template <class T>
typename Bin_treec<T>::Nodo Bin_treec<T>::root() const
{
return(inizio);
}
template <class T>
typename Bin_treec<T>::Nodo Bin_treec<T>::parent(Nodo n) const
{
if (n != inizio)
return (spazio[n].genitore);
else
return(n);
}
template <class T>
typename Bin_treec<T>::Nodo Bin_treec<T>::sx(Nodo n) const
{
if (!sx_empty(n))
return (spazio[n].sinistro);
else
return(n);
};
template <class T>
typename Bin_treec<T>::Nodo Bin_treec<T>::dx(Nodo n) const
{
if (!dx_empty(n))
return (spazio[n].destro);
else
return(n);
}
template <class T>
bool Bin_treec<T>::sx_empty(Bin_treec<T>::Nodo n) const
{
return (spazio[n].sinistro == NIL);
}
template <class T>
bool Bin_treec<T>::dx_empty(Bin_treec<T>::Nodo n) const
{
return (spazio[n].destro == NIL);
}
template <class T>
void Bin_treec<T>::ins_root()
{
if (inizio == NIL)
{
inizio = libera;
libera = spazio[libera].sinistro;
spazio[inizio].sinistro = NIL;
spazio[inizio].destro = NIL;
nNodi++;
}
else
throw RootExists();
}
template <class T>
void Bin_treec<T>::ins_sx(Nodo n)
{
if (inizio == NIL)
throw EmptyTree();
if (n == NIL)
throw NullNode();
if (spazio[n].sinistro != NIL)
throw NodeExists();
if (nNodi >= MAXLUNG)
throw FullSize();
else
{
Nodo q = libera;
libera = spazio[libera].sinistro;
spazio[n].sinistro = q;
spazio[q].sinistro = NIL;
spazio[q].genitore = n;
spazio[q].destro = NIL;
nNodi++;
}
}
template <class T>
void Bin_treec<T>::ins_dx(Nodo n)
{
if (inizio == NIL)
throw EmptyTree();
if (n == NIL)
throw NullNode();
if (spazio[n].destro != NIL)
throw NodeExists();
if (nNodi >= MAXLUNG)
throw FullSize();
else
{
Nodo q = libera;
libera = spazio[libera].sinistro;
spazio[n].destro = q;
spazio[q].genitore = n;
spazio[q].sinistro = NIL;
spazio[q].destro = NIL;
nNodi++;
}
}
template <class T>
void Bin_treec<T>::erase(Nodo n)
{
if (n != NIL) {
if (!sx_empty(n))
erase(spazio[n].sinistro);
if (!dx_empty(n))
erase(spazio[n].destro);
if (n != inizio) {
Nodo p = parent(n);
if (spazio[p].sinistro == n)
spazio[p].sinistro = NIL;
else
spazio[p].destro = NIL;
}
else
inizio = NIL;
nNodi--;
spazio[n].sinistro = libera;
libera = n;
}
else
throw NullNode();
}
template <class T>
T Bin_treec<T>::read(Nodo n) const
{
if (n != NIL)
return (spazio[n].valore);
else
throw NullNode();
}
template <class T>
void Bin_treec<T>::write(Nodo n, value_type a)
{
if (n != NIL)
spazio[n].valore = a;
else
throw NullNode();
}
#endif /* _Bin_treecC_H_ */
this is the main
#include "util_bin_tree.h"
#include <iostream>
using namespace std;
int main() {
Bin_treec<int> T;
typename Bin_treec<int>::Nodo n1 = 0, n2 = 0;
T.ins_root();
T.write(T.root(), 1);
n1 = T.root();
T.ins_sx(n1);
T.ins_dx(n1);
T.write(T.sx(n1), 2);
n1 = T.dx(n1);
T.write(n1, 3);
T.ins_dx(n1);
T.write(T.dx(n1), 4);
T.print();
cout << T;
n_leaf(T); // here i have error C3681
It says that my function is undeclared but i don't know why.
Full error is :
Severity Code Description Project File Line Suppression State
Error C3861 'n_leaf': identifier not found esercizio C:\Users\mypc\source\repos\esercizio\test.cpp 26
I also have a virtual bin_tree header where util_bin_tree is not specified, but I don't think it really matters because i don't use any functions related to the tree.
Also, is it my way to pass an array from T correct? I just wanted to pass an entire object to another class function and the compiler doesn't find any error for the time being. But i can't test the function just because of that problem. Any help?
Your n_leaf function is not a namespace-scoped function, it's a static function inside the util_bin_tree class. You can call it with util_bin_tree<int>::n_leaf(T).
Since your util_bin_tree class does not have any data members, you could use namespace util_bin_tree { } instead, and put template<class T> before each function.

Unable to Access Struct Members within Template

I decided to make my HashTable class a template so I could practice making templates, but I've run into a problem. Within my HashTable<T> template, I have a data member array, called items of Buckets, which is a struct within the HashTable<T> class. After initializing items, I am unable to access the members of Bucket elsewhere in the template's code.
I have tried putting typename and template<class T> before the struct and variable definitions, but was unable to make it work.
Here is a snippet of code that gives me the error 'keyValue': undeclared identifier
#ifndef HASH_TABLE_
#define HASH_TABLE_
using namespace std;
#include <iostream>
template<class T>
class HashTable
{
public:
HashTable(int numItems) {
if (numItems <= 0) {
throw std::invalid_argument("Invalid HashTable size");
}
currItems = 0;
//B must be the next prime after 2 * numItems
B = 1000;
items = Bucket[B]; //allocate array of Buckets
items[0].keyVal; //ERROR: undeclared identifier
}
bool insert(T* newItem, int key) {
bool retVal = false;
if (currItems < B && newItem != NULL) { //cannot insert to full HashTable
int index = 0;
items[index].dataPtr = newItem; //ERROR:undeclared
items[index].keyVal = key; //ERROR:undeclared
retVal = true;
currItems++;
}
return retVal;
}
private:
struct Bucket {
T* dataPtr = NULL;
int keyVal = -1;
};
Bucket * items; //array of buckets
int B; //size of itemArray
int currItems; //track number of items in HashTable
};
#endif
Why does items[x] not access a Bucket, such that items[x].keyVal or items[x].dataPtr cannot be used? I've tried different types of initializations, such as items = new Bucket[B], but that hasn't worked either, so I am assuming my errors lie in the template side of things.
I appreciate any guidance!
You have to declare Bucket before you use it.
template<class T>
class HashTable
{
struct Bucket {
T* dataPtr = NULL;
int keyVal = -1;
};
public:
HashTable(int numItems) {
if (numItems <= 0) {
throw std::invalid_argument("Invalid HashTable size");
}
currItems = 0;
//B must be the next prime after 2 * numItems
B = nextPrime(numItems * 2);
items = new Bucket[B]; // <-- you forgot the 'new'
items[0].keyVal; //ERROR: undeclared identifier
}
bool insert(T* newItem, int key) {
bool retVal = false;
if (currItems < B && newItem != NULL) { //cannot insert to full HashTable
int index = getOpenBucket(key);
items[index].dataPtr = newItem; //ERROR:undeclared
items[index].keyVal = key; //ERROR:undeclared
retVal = true;
currItems++;
}
return retVal;
}
private:
Bucket * items; //array of buckets
int B; //size of itemArray
int currItems; //track number of items in HashTable
};
ps. do not do this: using namespace std; in header files - ever.
It is evil and antisocial as it poisons the global namespace of every cpp file that includes your header. It's a guaranteed way to ensure that no-one will ever use your library.

Check for changes in POD variables

I'm looking for an efficient way to check if a POD variable is altered between two cycles. I've come up with this solution:
class Foo {
public:
template<typename T>
bool isChanged(T& entry);
void endCycle();
private:
std::map<void*,size_t> entryMap; // <Address orig.,Size>
std::map<void*,void*>oldVals; // <Address orig., Address cpy.>
};
template<typename T> bool Foo::isChanged(T& entry)
{
entryMap[&entry] = sizeof(T);
if(oldVals[&entry] == NULL)
return false;
if(memcmp(&entry, oldVals[&entry], entryMap[&entry]))
return true;
else
return false;
}
void Foo::endCycle()
{
// Copy all the bytes to save them for the next cycle
for( std::map<void*,size_t>::iterator entryIt = entryMap.begin();
entryIt != entryMap.end();
++entryIt)
{
if(oldVals[entryIt->first] == NULL)
oldVals[entryIt->first] = malloc(entryIt->second);
memcpy(oldVals[entryIt->first], entryIt->first, entryIt->second);
}
}
Now i can use it like this:
Foo gBar;
void aFunction()
{
int ar;
char ba[3][3];
// Some code where ar and ba are filled
if(gBar.isChanged(ar))
// Do Something
if(gBar.isChanged(ba))
// Do Something
gBar.endCycle();
}
Is this an efficient way? My goal was a method which is very easy to use inside various cyclically called functions. I cleaned all the init and free logic from the code. Any suggestions? I especially don't like the oldshool malloc, memcpy and memcmp stuff but i don't know any other way how to do it.
Edit: Found a good solution based on Red Alerts suggestions.
I think you can use templates a little more effectively here.
template <typename T>
class Foo
{
public:
static std::map<T*, T> values;
static bool isChanged(T& entry)
{
auto it = values.find(&entry);
if(it == values.end())
{
values[&entry] = entry;
}
else if(entry != it->second)
{
it->second = entry;
return true;
}
return false;
}
};
template <typename T>
std::map<T*, T> Foo<T>::values;
int main() {
int ar = 3;
cout << Foo<int>::isChanged(ar) << endl; // 0
ar = 4;
cout << Foo<int>::isChanged(ar) << endl; // 1
for(auto& value : Foo<int>::values)
cout << value.second << endl; // 4
return 0;
}
This way you get one map per type, and you don't have to worry about inadvertently messing up an alias. You do need to define operator != and have a working copy constructor for your types, but that is much better than blindly using memcmp and memcpy.
You can also make further template specializations for arrays if you need to compare those (will be a bit more code, but nothing very complicated)
Edit: To get you started, this is what your template signature should look like:
template<class T, size_t N> bool isChanged(T(&entry)[N]); //will be called for stack allocated arrays
Or you can use char* to alias all of your values. This will let you use a single map for everything (like you were doing before, but this has no memcpy/memcmp). It will only work for POD. We could manually call the destructor when overwriting the buffer, but since there is no good way to do this in the class's destructor, it's probably best to leave out heap allocated data altogether.
class Foo
{
std::map<char**, char*> values;
public:
~Foo()
{
for(auto& value : values)
{
delete[] value.second;
}
}
template<typename T> bool isChanged(T& entry)
{
char** addr = reinterpret_cast<char**>(&entry);
auto it = values.find(addr);
if(it == values.end())
{
alignas(T) char* oldBuf = new char[sizeof(T)];
T* oldEntry = new(oldBuf) T;
*oldEntry = entry;
values[addr] = oldBuf;
}
else if(entry != *(reinterpret_cast<T*>(it->second)))
{
T* oldEntry = new(it->second) T;
*oldEntry = entry;
return true;
}
return false;
}
};
After many hours i think i found a good solution. The call stays easy and there are no casts. It's a lot more complex than the C-Style version with memcopy but I think its nicer and has also the benefit that it works with complex data not just POD.
class Manager
{
public:
~Manager()
{
funcPtrs.clear();
}
void adFnc(void(*function)())
{
funcPtrs.push_back(function);
}
void runAll()
{
for(auto& val : funcPtrs)
val();
}
private:
std::vector<void (*)()> funcPtrs;
};
Manager gAllClearManager;
template<typename T>
class Data
{
public:
Data()
{
gAllClearManager.adFnc(clearValues);
}
static void clearValues()
{
values.clear();
}
static std::map<T*,std::vector<T>>& getValues() { return values; }
private:
static std::map<T*,std::vector<T>> values;
};
template <typename T>
static bool isChanged(T& entry)
{
const static Data<T>* dataP = new Data<T>();
static std::map<T*,std::vector<T>>& values = dataP->getValues();
auto it = values.find(&entry);
if(it == values.end())
{
values[&entry].push_back(entry);
}
else if(entry != it->second[0])
{
it->second[0] = entry;
return true;
}
return false;
}
template<typename T, size_t N>
bool isChanged(T (&entry)[N])
{
const static Data<T>* dataP = new Data<T>();
static std::map<T*,std::vector<T>>& values = dataP->getValues();
auto it = values.find(entry);
if( it == values.end())
{
for(int i = 0; i < N ; ++i )
values[entry].push_back(entry[i]);
return false;
}
else
{
for(int i = 0; i < N ; ++i )
{
if(it->second[i] != entry[i])
{
for(int j = 0; j < N ; ++j )
{
it->second[j] = entry[j];
}
return true;
}
}
}
return false;
}
template<typename T>
std::map<T*, std::vector<T>> Data<T>::values;
Now i can use it like:
int main() {
int ar;
std::string ba[6];
if(isChange(ar))
// Do something
if(isChange(ba))
// Do something
}
My first template is finally working! :) Thanks again Red Alert.

Use of pointers in a stack class?

I'm learning C++, and we were given an exercise to make a stack class using a class template and pointers. I'm not yet fully understanding the implementation of a stack or pointers so I gave it a go and made this class:
template <class T>
class Stack_Class {
public:
T* stack;
int item_quantity;
T* First_item;
int Max_quantity;
Stack_Class(int value);
~Stack_Class();
bool Add(T value);
T Pop();
int GetMax_Quantity();
bool Full();
bool Empty();
};
template <class T>
Stack_Class<T>::Stack_Class(int value) {
if (value > 0) {
stack = new T[value];
First_item = stack;
item_quantity = 0;
Max_quantity = value;
}
}
template <class T>
Stack_Class<T>::~Stack_Class() {
if (First_item) {
delete First_item;
}
}
template<class T>
bool Stack_Class<T>::Add(T num) {
if (item_quantity <Max_quantity) {
*stack = num;
stack++;
item_quantity++;
return true;
}
else return false;
}
template<class T>
T Stack_Class<T>::Pop() {
if (!Empty()) {
item_quantity--;
return stack[item_quantity];
}
return NULL;
}
template<class T>
bool Stack_Class<T>::Empty() {
return (item_quantity == 0);
}
template <class T>
int Stack_Class<T>::GetMax_Quantity() {
return Max_quantity;
}
And the main class would be:
#include <iostream>
#include "Stack_Class.h"
void main() {
Stack_Class<int> intStack(3);
intStack.Add(1);
intStack.Add(2);
intStack.Add(3);
int count = intStack.GetMax_Quantity();
for (int i = 0; i < count; i++) {
std::cout << "Pop No: " << i << " - Elemento: " << intStack.Pop() << std::endl;
}
}
Though as a result I'm getting all random numbers instead of the ones I gave it in intStack. Add, so my question would be I'm implementing the pointer correctly here?
You need to deincrement the stack pointer before you reference it within Pop():
template<class T>
T Stack_Class<T>::Pop(){
if (!Empty()){
item_quantity--;
stack--;
return *stack;
}
return NULL;
}
Your array access stack[item_quantity] does not work because you increment stack in Add. So after construction, the memory pointed to by stack looks like this
0xff65f96f <-- *(stack + 0)
0x0eec604f <-- *(stack + 1)
0x05be0582 <-- *(stack + 2)
0x29b9186e <-- *(stack + 3)
The hexdecimal values represent random garbage coincidentely located in the memory at the time of allocation. This is because memory allocated by new is not initialized to something nice. After adding three values, it looks like this
1 <-- *(stack - 3)
2 <-- *(stack - 2)
3 <-- *(stack - 1)
0x29b9186e <-- *(stack + 0)
0xf66eff06 <-- *(stack + 1)
0x357eb508 <-- *(stack + 2)
In the first call of Pop, you access stack[2] = *(stack + 2), because item_quantity is 2 after deincrementing it. The two consecutive calls to Pop access stack[1] and stack[0]. As you can see above, you never actually reference the values you’ve put into the stack.
You are mixing up the pointer incrementing semantic in the Add method and the indexing semantic in the Pop method.
Since you need the index for the Empty method and so on, I would fix your Add method instead of the Pop as can be seen below.
Otherwise, you would end up still using the indexing in some method(s), but not in other. It would not look consistent to me.
template<class T>
bool Stack_Class<T>::Add(T num){
if (item_quantity <Max_quantity){
stack[item_quantity++] = num;
return true;
}
else return false;
}
Yet another problem in your code is this:
stack = new T[value];
but you seem to only delete the first element in the pointer. That is a guaranteed (and potentially not negligible) memory leak.
Even if you fix all that, your code would not still compile since you are trying to return void, whereas a C++ program should return int, so change this:
void main(){
...
}
to:
int main(){
...
}
... and return an integer like 0 correspondingly.
You would also need to fix this warning:
Stack_Class.h:56:13: warning: converting to non-pointer type ‘int’ from NULL [-Wconversion-null]
return NULL;
^
By for instance change NULL to 0.
Having fixed all that, the output is like this:
Pop No: 0 - Elemento: 3
Pop No: 1 - Elemento: 2
Pop No: 2 - Elemento: 1
You can also see the code running on ideone.
For your convenience, this is the whole working code after those fixes:
template <class T>
class Stack_Class{
public:
T* stack;
int item_quantity;
T* First_item;
int Max_quantity;
Stack_Class(int value);
~Stack_Class();
bool Add(T value);
T Pop();
int GetMax_Quantity();
bool Full();
bool Empty();
};
template <class T>
Stack_Class<T>::Stack_Class(int value){
if (value > 0){
stack = new T[value];
First_item = stack;
item_quantity = 0;
Max_quantity = value;
}
}
template <class T>
Stack_Class<T>::~Stack_Class(){
if (First_item){
delete First_item;
}
}
template<class T>
bool Stack_Class<T>::Add(T num){
if (item_quantity <Max_quantity){
*stack = num;
stack++;
item_quantity++;
return true;
}
else return false;
}
template<class T>
T Stack_Class<T>::Pop(){
if (!Empty()){
item_quantity--;
return stack[item_quantity];
}
return NULL;
}
template<class T>
bool Stack_Class<T>::Empty(){
return (item_quantity == 0);
}
template <class T>
int Stack_Class<T>::GetMax_Quantity(){
return Max_quantity;
}