Abstract data types using typename in C++


C++ has some really great advantages over languages like Java. It allows for abstract data types using the keyword typename. In this simple program, I create a class called Array and pass to it a typename and an integer to declare its size. I’m then able to assign array elements a value that corresponds to the data type I assigned it.

I use three typenames in the example, including int, double, and char.

Running

Source Code

main.cpp

#include <iostream>
#include "array.h"
using namespace std;
int main(int argc, char** argv)
{
  Array<int, 5> data1;
  data1[3] = 3;
  cout << data1[3] << endl;
  Array<double, 2> data2;
  data2[2] = 7.6;
  cout << data2[2] << endl;
  Array<char, 2> data3;
  data3[2] = 'H';
  data3[5] = 's';
  cout << data3[2];
  cout << data3[5];
  return 0;
}

array.h

#ifndef ARRAY_H
#define ARRAY_H

template <typename T, int N>
class Array
{
	public:
	  Array()
	  {
	    size = N;
	    data = new T[size];
	  }
	  T& operator[](int index)
	  {
	    return data[index];
	  }
	  ~Array()
	  {
	    if (data) delete[] data;
	  }
	private:
	  T *data;
	  int size;
};

#endif
,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: