C++/Templates 2

From Wikiversity
< C++
Jump to: navigation, search

Templates 2[edit]

Templates can also be used with classes

using namespace std;

template <class T>
class myClass
{
		// Attributes
		T * storage;
		int NElements;
	public:
		// Constructors & Destructor
		myClass(int size = 1)
		{
			storage = new T[size];
			NElements = size;
		}
		~myClass() {delete [] storage;}
		// Methods
		int GetSize() {return NElements;}
		T GetVal(int place) {return storage[place];}

		void SetVal(int place, T val)
		{
			if (place + 1 > NElements)
			{ cout << "Cannot place a value at position " << place << endl; return; }
			storage[place] = val;
		}
		void push(T val) { SetVal(NElements++, val); }
		void pop() { NElements--; }
};
int main()
{
	myClass<int> mc1;
	for (int i = 0 ; i < 10 ; i++)
		{ mc1.push((i + 1)*(i + 1)); }

	for (int i = 0; i < mc1.GetSize() ; i++)
		{ cout << mc1.GetVal(i) << endl; }
	
	cout << "-------------\n";
	
	myClass<char> mc2;
	for (int i = 0 ; i < 26 ; i++)
		{ mc2.push((char) i+97); }

	for (int i = 0; i < mc2.GetSize() ; i++)
		{ cout << mc2.GetVal(i) << endl; }

	return 0;
}

Where To Go Next[edit]

Topics in C++
Beginners Data Structures Advanced
Part of the School of Computer Science