Moreover, the whole idea behind all of these methods is re-use of code... It'll take a little longer to get the class going the first time, but after that you can re-use the code over and over.
virtual functions are best when you want to have an array of assorted objects at once... All you need is a base class, and you can run through the container calling a function (say f()) of different classes, regardless of if f is of class A or B.
For instance, lets consider this:
you have a container (an array/linked list what have you) of BASE pointers, that point to objects derived from base that are either DER1 or DER2... each have the function f() (which was declared pure virtual in the base) and have overriden it.
Code:
//BASE.h
class BASE
{
public:
...
...
Code:
class DER1
{
public:
virtual void f(){/*some stuff*/}
}
...
Code:
class DER2
{
public:
virtual void f(){/*some other stuff*/}
}
...
Code:
//main.cpp
//after assigning the pointers to objects of DER1 and DER2
for(size_t i = 0; i < size; i++)
{
container[i]->f();
//for objects of type DER1, this will call DER1.f()
//for objects of type DER2, this will call DER2.f()
}
Note: The BASE class is abstract, and you
cannot declare objects of BASE type, but you can have pointers of the BASE type pointing to derived objects...
Factories, Singlton and the like are very useful.
Templates are just as Mahesh has discribed. The best example of usefulness is the STL... For instance, look at the vector.
Code:
vector<int> INTS(3,5);
vector<char> CHARS(100,'a');
One time writting the class, no need to edit the vector.h or vector.cpp to make it use ints or chars, just use it's template. Usefule STL stuffs:
- map (hashtable data type, required a comparison function lessthan or operator < (can't remember which))
- set (binary search tree, same requirements as MAP)
- vector (Dynamic array, any first class object or data type)
- list (linked list, any first class object)
- stack (see vector)
- deque (see list)
They come with nested templated interators, and the STL has an algorithm library for easy ability to sort, remove duplicates and any other common container operation... Templates and the STL make life REALLY easy.