Introduction
- Class
- private versus public members
- data members are usually kept private
- access to the data members through the public member functions
- How to write the member functions
- first.cpp
- Inline functions
- Implemented efficiently
- one or two line code for the member functions can be just
put in the class definition itself (animal1.cpp)
- Template
- animal1.cpp has a class that works only for dogs
- if we wanted similar class for cats, we will have to copy
all the code for chaos_animal and replace dog with cat
- Repetition
- Repetition can lead to erroneous code
- Use a template for chaos_animal
- General format of templates is
template <parameter-list>
class-definition or function-definition
- Parameter list can consist of one or more parameters sparated
by a comma. The parameters can be any one of the basic types such
as int, char, double, etc. A special type of parameter is called
class. A parameter of the type class is used to specify the data
types in C++.
template <class animal_type, int max_animals>
class chaos_animal
{
animal_type animal[max_animals];
public:
void cacophony();
};
- The class definition can use any one of the parameters defined
in the parameters. The above example, uses animal_type and max_animals
in the class definition
- The function definition is any valid function that uses any
one of the parameters defined in the parameters.
template <class animal_type, int max_animals>
void chaos_animal<animal_type,max_animals>::cacophony()
{
#include <time.h>
template <class algorithm_type>
class timer
{
public:
time_t timed(int n, algorithm_type t);
};
template <class algorithm_type>
time_t timer<algorithm_type>::timed(int n, algorithm_type
t)
{
}
class dummy
{
public:
void work(int n){}
};
void main()
{
timer<dummy> test;
}
- Here we have two templates. Both templates take one parameter
called algorithm_type which will be a valid class definition in
C++.
- First template is for a class called timer. The class timer
has a function member called timed which takes two parameters:
one of type int and the other of type algorithm_type (from the
parameter list of template) and returns a value to the type time_t
(predefined in BC++).
- The second template is for a function called timed which takes
two parameters: one of type int and the other of type algorithm_type
and returns a value to the type time_t (predefined in BC++). This
function happens to be a member function of timer<algorithm_type>.