I am a student programmer learning my first language with the book "Accelerated C++." I am at at a point where the author is explaining header files and source files containing functions. In the exercise the book provides for explanation, the author has header files that contain the definitions for functions, but it seems redundant as the source file also has the definition for the functions. What is the point of a header file in this case when programming C++?
Example: Header file.
#ifndef MEDIAN_H
#define MEDIAN_H
#include <vector>
double median(std::vector<double>);
#endif // MEDIAN_H
Then source file containing function to determine the median of grades:
// source file for the `median' function
#include <algorithm> // to get the declaration of `sort'
#include <stdexcept> // to get the declaration of `domain_error'
#include <vector> // to get the declaration of `vector'
using std::domain_error; using std::sort; using std::vector;
#include "median.h"
// compute the median of a `vector<double>'
// note that calling this function copies the entire argument `vector'
double median(vector<double> vec)
{
#ifdef _MSC_VER
typedef std::vector<double>::size_type vec_sz;
#else
typedef vector<double>::size_type vec_sz;
#endif
vec_sz size = vec.size();
if (size == 0)
throw domain_error("median of an empty vector");
sort(vec.begin(), vec.end());
vec_sz mid = size/2;
return size % 2 == 0 ? (vec[mid] + vec[mid-1]) / 2 : vec[mid];
}
The median.h is copied into the median function source file even though the source already has the definition vector<double> vec
The book explains it as harmless and actually a good idea. But I just want to get a better understanding of the reason for such redundancy. Any explanation would be great!