Abstract Data Types (ADTs) Class Templates
Abstract Data Types (ADTs) Class Templates
A list of operations
ADT FORMAT
For each operation we specify:
The input values that are
provided by the client
Preconditions that must apply to
the data before the operation can
be performed
The process that is performed by
the operation
ADT FORMAT
After execution the operation, we
specify:
The output values that are
returned to the client
The post conditions that indicate
any changes in the data
NOTE:
Most ADTs have an initializer operation that
assigns initial values to the data (constructor in
C++)
ADT FORMAT
Example
template<class T>
MyClass< T >::MyClass(int size)
{
myArray = new T[size];
}
• Constructor definition - creates an array of type T
Class Templates
template <typename T>
Notice that parameterized
class Array {
type T must be specified
public:
repeatedly in class template
Array(const int size);
~Array(); When an instance is
private: declared, must also explicitly
T *m_values; specify the concrete type
const int m_size; parameter
}; E.g., int in function main()
int main() {
Array <int> a(10);
return 0;
}
Functions
“FindMax” Example
int FindMax(int x, int y)
{
int maximum;
if(x>=y)
maximum = x;
else
maximum = y;
return maximum;
}
“FindMax” Example (cont.)
#include <iostream.h>
int FindMax(int, int); // function prototype
int main()
{
int firstnum, secnum, max;
cout << "\nEnter two numbers: ";
cin >> firstnum >> secnum;
max=FindMax( firstnum, secnum); // the function is called here
cout << "The maximum is " << max << endl;
return 0;
}
Formal Parameters
• The argument names in the function header are
referred to as formal parameters.
if(x>=y)
x, y are called
maximum = x;
else “formal parameters”
maximum = y;
return maximum;
}
Calling a function by “value”
#include <iostream.h>
int FindMax(int, int); // function prototype
int main()
{ firstnum, secnum are called
int firstnum, secnum, max; “actual parameters”
cout << "\nEnter two numbers: ";
cin >> firstnum >> secnum;
max=FindMax( firstnum, secnum); // the function is called here
cout << "The maximum is " << max << endl;
return 0;
}
Calling a function by value (cont.)
#include <iostream.h>
void newval(float, float); // function prototype
int main()
{
float firstnum, secnum;
cout << "Enter two numbers: ";
cin >> firstnum >> secnum;
newval(firstnum, secnum);
cout << firstnum << secnum << endl;
return 0;
}
void main()
{
int x = 3;
int& y = x;
cout << "x= " << x << "y = " << y << endl;
y = 7;
cout << "x= " << x << "y = " << y << endl;
}
Reference variables and pointers
void main()
{
const numElems = 5;
int arr[numElems] = {2, 18, 1, 27, 16};
avg=0.0;
for(i=0; i<n; i++)
avg += vals[i];
avg = avg/n;
return avg;
}
Dynamic 1D Array
Allocation/ Deallocation
int *arr;
delete [] arr;
Dynamic 1D arrays
as function arguments
float find_average(int *, int);
void main()
{
int *arr, numElems;
float average;
avg=0.0;
for(i=0; i<n; i++)
avg += vals[i];
avg = avg/n;
return avg;
}