0

I'm curious about something when creating a new class in c++.

In my main.cpp I have both of these:

#include <iostream> 
#incude <string>

However, in the header file of my other class, FeedInfo.h, what do I need to include to be able to use strings there as well?

For example, If I want to create a string in my .h:

std::string feed;

This code will successfully compile when I only use #include <iostream> OR when i only use #include <string> -- or when I use both, of course.

This confused me because in main.cpp I have to use both - but in .h file I only need one of them - so which one do I include?

Thank you.

  • 1
    You should look at some documentation. `::std::string` is defined in ``. Even though it can be included in some other headers (such as``) you can not rely on such behavior. – user7860670 Jan 06 '18 at 19:32
  • 1
    If you use `std::string` then include `` and if you use `std::cout` then include ``. – Galik Jan 06 '18 at 20:02

1 Answers1

1

On some implementations the <iostream> header includes the <string> header so you are relying on a free ride. That should be avoided and you should explicitly include the <string> header when working with std::string type. For example this:

#include <iostream>

int main() {
   std::string s = "Hello World!";
   std::cout << s;
}

compiles when using g++, it does not compile when using Visual C++. So you should use:

#include <iostream>
#include <string>

int main() {
   std::string s = "Hello World!";
   std::cout << s;
}

In short, if you need a std::string - include the <string> header where appropriate, if you want to send data to standard output use <iostream>. Here is a breakdown when using headers and source files:

myclass.h:

#ifndef MY_CLASS_H
#define MY_CLASS_H

#include <string>
 // your code

#endif 

myclass.cpp:

#include "myclass.h"
// include other headers as needed

main.cpp:

#include <iostream>
#include <string>
#include "myclass.h"
//your code

Also take a look at this question titled: How do I include the string header?

Ron
  • 14,674
  • 4
  • 34
  • 47