Toy_Soldier Toy_Soldier - 2 months ago 6
C++ Question

Stuck at the usage of string library

My header file goes like this:

//Sales_data.h
#ifndef SALES_DATA_H
#define SALES_DATA_H

//#include<string>

struct Sales_data
{
std::string bookNo; //compiles without error
};
#endif


Usually, we include the
string
header whenever we have to use string variables in our code. But the program using the above header compiles without any errors even though I am not including the
string
header in the program.

Answer

This is a function of your specific compiler/implementation of the standard library. Generally speaking, to make your code 100% portable, you should include the string header, because not every compiler will do this. I know that current versions of both gcc and clang allow it (I'm uncertain about MSVC), but in order to make your code standards-compliant, you should always include the string header where you want to use std::string. If you ever find yourself having to develop for a platform where the compiler doesn't do this, the code you've given above will fail to compile and you'll have to spend time and effort debugging it. So why bother? Toss in that #include <string>, keep programming, and save yourself the trouble of fixing it later.

Comments