I'm trying to learn the bases of c++.
In a book, there is this:
For example, because our Sales_data class has a string member, Sales_data.h must #include the string header. As we’ve seen, programs that use Sales_data also need to include the string header in order to use the bookNo (member if Sales_data)
Short question: Actually I need a theoric explanation of this: if I include an header which is using std::string (so it imports string), why I need to import again in the main program using the header ?
Long question
I tried to create a demo program like this:
Sales_data.h
#include <string>
struct Sales_data {
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};
prog2.cpp
#include <iostream>
#include "Sales_data.h"
int main()
{
Sales_data data1, data2;
double price = 0; // price per book, used to calculate total revenue
std::cin >> data1.bookNo >> data1.units_sold >> price;
data1.revenue = data1.units_sold * price;
std::cin >> data2.bookNo >> data2.units_sold >> price;
data2.revenue = data2.units_sold * price;
if (data1.bookNo == data2.bookNo) {
unsigned totalCnt = data1.units_sold + data2.units_sold;
double totalRevenue = data1.revenue + data2.revenue;
std::cout << data1.bookNo << " " << totalCnt
<< " " << totalRevenue << " ";
if (totalCnt != 0)
std::cout << totalRevenue/totalCnt << std::endl;
else
std::cout << "(no sales)" << std::endl;
return 0; // indicate success
} else {
std::cerr << "Data must refer to the same ISBN"
<< std::endl;
return -1; // indicate failure
}
}
Actually, I compiled it, under Linux with
g++ prog2.cpp -o prog2 -std=c++11
But it runs without need to #include <string> in the prog2.cpp code.
So: is it the book in error, or it's a 'case' because g++ work well anyway ?
Please note that in book's code there is a #include <string> also in prog2.cpp file, so I cannot understand if it's better or it's mandatory, but it works fine without it !
*Important edit *
The book itself is telling me this:
As a result, programs that use Sales_data will include the string header twice: once directly and once as a side effect of including Sales_data.h. Because a header might be included more than once, we need to write our headers in a way that is safe even if the header is included multiple times