Using declarations and not using them.

Hello! I am a noob on the most extreme side of the scale. I am currently going through the tutorial and ran into an issue regarding the equivalence of two programs. I am using cpp.sh.

This is the code copied directly from the tutorial.

1
2
3
4
5
6
7
8
9
10
11
12
// my first string
#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string mystring;
  mystring = "This is a string";
  cout << mystring;
  return 0;
}


Previously in the tutorial, it stated: "Both ways of accessing the elements of the std namespace (explicit qualification and using declarations) are valid in C++ and produce the exact same behavior".

Naturally, that statement led me to try this:

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>

int main ()
{
  string mystring;
  mystring = "This is a string";
  std::cout << mystring;
  return 0;
}


But of course this didn't work and the error told me to write "std::string"

Okay, sure.

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>

int main ()
{
  std::string mystring;
  mystring = "This is a string";
  std::cout << mystring;
  return 0;
}


This works, but I don't understand why I have to put std:: in front of string. In the tutorial they say this string is a compound type, so I assume that cout is also a compound type, but from there I'm lost.

Can someone please talk to me about compound types and maybe nudge me in a direction of study? Thank you for your time.
What do you mean by "compound type"? The reason you must put std:: in front of string is because string, like cout, is in the std namespace and that is how you access things inside namespaces.
When I said it's a compound type, I was going off of this statement in the tutorial.

"Fundamental types represent the most basic types handled by the machines where the code may run. But one of the major strengths of the C++ language is its rich set of compound types, of which the fundamental types are mere building blocks."

"The string class is a compound type. As you can see in the example above, compound types are used in the same way as fundamental types: the same syntax is used to declare variables and to initialize them."

Based off what you said, I guess I have to look into namespace more. Thank you.
Ah, I see. Compounds types have nothing to do with namespaces.
Topic archived. No new replies allowed.