Why do we need to include headers (like string
, iostream
) into a header containing the class definition (class requires I/O or string proration) - as the headers are already included into the cpp translational unit where this class header is included.
It seems like doubling the content. Isn't the header material first pasted into the the cpp file where it has been included?
example:
//HEADER
#ifndef SAMPLE_H
#define SAMPLE_H
class sample
{
public:
sample();
}
sample::sample()
{
cout<<"Constructor!!!\n"; //error
}
#endif
//CPP
#include<iostream>
#include"m.h"
using namespace std;
int main()
{
m obj();
return 0;
}
The error thrown is:
error: ‘cout’ was not declared in this scope
Even when i have used using namespace std
in the cpp file. So either I have to include iostream
in the class definition file or use std
before using cout
- But why? Since the iostream
and namespace has already been included into the main translational unit.