473,396 Members | 1,766 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Why do we have to define a namespace with string header?

I know that it's a very basic question, but I can't figure out or find
an answer to why do we have to specify a namespace, like this

#include<string>
using namespace std;

when using the standard string library? Is this really necessary, why?
Thanks,

Bernhard Enders.

May 10 '06 #1
12 2148
bgeneto wrote:
I know that it's a very basic question, but I can't figure out or find
an answer to why do we have to specify a namespace, like this

#include<string>
using namespace std;

when using the standard string library? Is this really necessary, why?
Thanks,

Because the standard library functions are declared in the namespace std.

You have to fully qualify something declared in a namespace, otherwise
the compiler won't find the symbol.

I'd avoid the blanket 'using namespace' directive and either use fully
qualified names (line std::cout) or use specific using directives for
the items you want to use from the namespace (using std::cout; for
example).

--
Ian Collins.
May 10 '06 #2
bgeneto wrote:
I know that it's a very basic question, but I can't figure out or find
an answer to why do we have to specify a namespace, like this

#include<string>
using namespace std;

when using the standard string library? Is this really necessary, why?
Thanks,

Bernhard Enders.


When creating a library, it is generally a good idea to put any symbols
you define in their own namespace. Doing so severely decreases the
chances that names that you use will conflict with names in the library
you write conflicting with names in others' libraries. You might say
the designers of the C++ Standard Library were just following good style
and setting a good example by putting all their symbols in namespace
std.

--
Alan Johnson
May 10 '06 #3
Thanks for your explanation, if I understand well the string class and
possibly it's methods are defined in the namespace std within the
standard header <string>. If so, what is the point in doing this? Is it
any better compared to the old school? std sounds like a scope to me,
but what do we have defined without the scope std? No class, no
methods, nothing?
About your 'suggestion' to use full qualified names, I figure that I
must also use std::string in addition to std::cout, std::cin, etc... a
little cumbersome, no?

Thanks one more time,

Bernhard Enders.

May 10 '06 #4
bgeneto wrote:
Thanks for your explanation, if I understand well the string class and
possibly it's methods are defined in the namespace std within the
standard header <string>. If so, what is the point in doing this? Is it
any better compared to the old school? std sounds like a scope to me,
but what do we have defined without the scope std? No class, no
methods, nothing?
About your 'suggestion' to use full qualified names, I figure that I
must also use std::string in addition to std::cout, std::cin, etc... a
little cumbersome, no?

Cumbersome, but it avoids name collisions between symbols form the
standard library and others. That's why the standard library is in its
own namespace.

The 'old school' (and current C) resolved naming issues by using more
verbose names in an attempt to avoid ambiguities. At least with
namespaces you can dispense with the namespace prefix with an
appropriate using directive.

--
Ian Collins.
May 10 '06 #5
bgeneto wrote:
Thanks for your explanation, if I understand well the string class and
possibly it's methods are defined in the namespace std within the
standard header <string>. If so, what is the point in doing this?


The general set of keywords for C++ were invented in the 1980s.

The Standard Library - the most common and most useful things to do /with/
those keywords - was ratified in 1997.

This was a good thing because the library had time to mature.

But the new language specification had to preserve over a decade of legacy
code. The language committees could not tell everyone, "some of your
functions will now disappear, some will change their behavior, and some will
break your programs now". People would simply reject Standard C++, and keep
using the "ARM C++" and its defacto standard.

So the committee fixed this in one move by putting everything in The
Standard Library into one big namespace. Legacy code that did not declare
this namespace could continue to use their legacy libraries. You might find
your C++ implementation still contains files such as "iostream.h".

(Worse, code can also mix-and-match legacy and standard code. The less said
about that the better.)

So, if you need strings or "STL" containers, import their namespace. This is
a very minor detail of well-structured code.

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
May 10 '06 #6
bgeneto wrote:
About your 'suggestion' to use full qualified names, I figure that I
must also use std::string in addition to std::cout, std::cin, etc... a
little cumbersome, no?


Within a source file it doesn't matter too much. In that context you
know everything you need to know to tell if it is safe to issue a
'using' directive. It is still my personal preference to explicitly
name which symbols I'll be using. Example:
using std::cout ;
using std::endl ;

In a header file it is best to avoid a 'using' directive that brings
something into the global namespace, as you don't know when and where
that header will get included, and whether or not your 'using'
directives are going to cause trouble for the person doing the
including.

--
Alan Johnson
May 10 '06 #7
"Alan Johnson" <al****@no.spam.stanford.edu> wrote in message
news:e3**********@news.Stanford.EDU...
bgeneto wrote:
I know that it's a very basic question, but I can't figure out or find
an answer to why do we have to specify a namespace, like this

#include<string>
using namespace std;

when using the standard string library? Is this really necessary, why?
Thanks,

Bernhard Enders.


When creating a library, it is generally a good idea to put any symbols
you define in their own namespace. Doing so severely decreases the
chances that names that you use will conflict with names in the library
you write conflicting with names in others' libraries. You might say
the designers of the C++ Standard Library were just following good style
and setting a good example by putting all their symbols in namespace
std.


You might say that, if it were true. Unfortunately, the Standard C++
library incorporates the Standard C library and the old cfront iostreams
library, both of which were born before namespaces were invented. Thus,
practically *every* pre-standard C++ program broke. Of course, you can
patch most programs by changing a few header names and adding the
notorious "using namespace std", but the latter is actively discouraged
by those who believe in "good style".

Even with newly written code, namespace std causes problems, mostly
because not everything really lives there. Of course, you have some
simple rules:

-- If a name is all caps, it must be a macro, so you don't write std::
in front of it (except for FILE).

-- If a name is all lowercase, it must be a function or object, so
you must write std:: in front of it (except for assert, errno, and
setjmp).

-- If a name begins with an underscore, it must be reserved to the
implementation, so you shouldn't use it (except for _IOFBF, _IOLBF,
and _IONBF).

-- There are no names with mixed case (except for the macro L_tmpnam,
and more recently the function _Exit).

-- Otherwise, all names are in namespace std (except for those in
std::relops).

-- It is therefore safe to recycle a name from the Standard C library
as your own name with external linkage (as long as it's not in either
namespace std or the global namespace, or has extern "C" linkage).

Got all that?

It would have been far better to leave the Standard C++ library in
the global namespace, where it was born and grew up. You can still
use namespaces to protect your own code, and that is indeed good
style. But nobody seems to teach that.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
May 10 '06 #8
"Phlip" <ph******@yahoo.com> wrote in message
news:lQ*****************@newssvr27.news.prodigy.ne t...
bgeneto wrote:
Thanks for your explanation, if I understand well the string class and
possibly it's methods are defined in the namespace std within the
standard header <string>. If so, what is the point in doing this?
The general set of keywords for C++ were invented in the 1980s.


And many more were added during "standardization" in the 1990s.
And *lots* more library names (which are not keywords) were added
as well.
The Standard Library - the most common and most useful things to do /with/
those keywords - was ratified in 1997.

This was a good thing because the library had time to mature.
Some of it. And parts of it were paper tigers that were standardized
before they were ever implemented.
But the new language specification had to preserve over a decade of legacy
code. The language committees could not tell everyone, "some of your
functions will now disappear, some will change their behavior, and some
will break your programs now". People would simply reject Standard C++,
and keep using the "ARM C++" and its defacto standard.
But that's exactly what the C++ committee did do.
So the committee fixed this in one move by putting everything in The
Standard Library into one big namespace. Legacy code that did not declare
this namespace could continue to use their legacy libraries. You might
find your C++ implementation still contains files such as "iostream.h".
It's nice to think that the C++ committee wisely took a new departure
and made a point of staying out of the way of old library naming
practices, but this was not their goal in adding namespace std and
the new headers. It was the *vendors* who wisely retained the legacy
headers for many years.
(Worse, code can also mix-and-match legacy and standard code. The less
said about that the better.)
Maybe, but quite a lot *had* to be said about it, by those of us who had
to support customers through a decade of transition. You will *still*
see regular postings on these newsgroups along the lines of, "I included
<string>, so why isn't class string defined?"
So, if you need strings or "STL" containers, import their namespace. This
is a very minor detail of well-structured code.


I agree that importing the entire std namespace is often the best way
to repair the damage, but I'm in a tiny minority.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
May 10 '06 #9
P.J. Plauger wrote:
The general set of keywords for C++ were invented in the 1980s.


And many more were added during "standardization" in the 1990s.
And *lots* more library names (which are not keywords) were added
as well.


The point was the time delay between establishing enough of the core
language to write programs, and establishing a stable library.
The Standard Library - the most common and most useful things to do
/with/ those keywords - was ratified in 1997.

This was a good thing because the library had time to mature.


Some of it. And parts of it were paper tigers that were standardized
before they were ever implemented.


I'm sure some people could have said the exact right thing in fewer words,
but I couldn't. The question was why is the standard library inside
namespace std...
But the new language specification had to preserve over a decade of
legacy code. The language committees could not tell everyone, "some of
your functions will now disappear, some will change their behavior, and
some will break your programs now". People would simply reject Standard
C++, and keep using the "ARM C++" and its defacto standard.


But that's exactly what the C++ committee did do.


....and you are gainsaying minor details. Of course The Standard broke some
existing code, just as The C Standard broke some existing code.
So the committee fixed this in one move by putting everything in The
Standard Library into one big namespace. Legacy code that did not declare
this namespace could continue to use their legacy libraries. You might
find your C++ implementation still contains files such as "iostream.h".


It's nice to think that the C++ committee wisely took a new departure
and made a point of staying out of the way of old library naming
practices, but this was not their goal in adding namespace std and
the new headers. It was the *vendors* who wisely retained the legacy
headers for many years.


Yet if they had not added namespace std, the Standard language would have
been much harder to adopt for billions of lines of legacy code. So it's the
same difference, and it's an adequate way to explain the namespace std
system to a newbie.
(Worse, code can also mix-and-match legacy and standard code. The less
said about that the better.)


Maybe, but quite a lot *had* to be said about it, by those of us who had
to support customers through a decade of transition. You will *still*
see regular postings on these newsgroups along the lines of, "I included
<string>, so why isn't class string defined?"


That's not mix-and-match.
So, if you need strings or "STL" containers, import their namespace. This
is a very minor detail of well-structured code.


I agree that importing the entire std namespace is often the best way
to repair the damage, but I'm in a tiny minority.


I tried to say "import them from their namespace".

http://www.janko.at/Humor/Computerwe...pace%20std.htm

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
May 10 '06 #10

P.J. Plauger wrote:

It would have been far better to leave the Standard C++ library in
the global namespace, where it was born and grew up. You can still
use namespaces to protect your own code, and that is indeed good
style. But nobody seems to teach that.


But then you are assuming that everyone will have to learn the whole of
the standard library to know what is in it to avoid nameclashes.

You should be able to learn a subset of the language and use it. Most
of us do. I don't use <valarray>, rarely if ever use <locale>, don't
use any of the time-formatting stuff...

May 10 '06 #11
"Phlip" <ph******@yahoo.com> wrote in message
news:bv*******************@newssvr21.news.prodigy. com...
P.J. Plauger wrote:
The general set of keywords for C++ were invented in the 1980s.
And many more were added during "standardization" in the 1990s.
And *lots* more library names (which are not keywords) were added
as well.


The point was the time delay between establishing enough of the core
language to write programs, and establishing a stable library.


Sorry, but there was considerable overlap between evolving the language
and using the new features in the library. There are even cases where
the library required a language feature *before* it was settled by
the core language subcommittee.
The Standard Library - the most common and most useful things to do
/with/ those keywords - was ratified in 1997.

This was a good thing because the library had time to mature.


Some of it. And parts of it were paper tigers that were standardized
before they were ever implemented.


I'm sure some people could have said the exact right thing in fewer words,
but I couldn't. The question was why is the standard library inside
namespace std...


Because it seemed like a good idea to some, at the time. It is worth
noting that namespaces were voted into the draft C++ Standard in mid
1993, mostly as an aid for structuring the Standard C++ library;
but it quickly became apparent that the people pushing namespaces
had no idea how to use them for that purpose. As a result, the library
subcommittee revised the use of namespaces at *every* meeting for the
next two years. And they settled on the current usage over the
vehement objections of several major compiler vendors. It is no
surprise that, to this day, only one or two vendors fully conform
to the C++ Standard in the use of library namespaces. (The Dinkumware
library can be configured to do so, but practically all of our OEMs
choose not to, for good practical reasons.)

Thuse, namespace std was yet another paper tiger, which is *still*
being debugged.
But the new language specification had to preserve over a decade of
legacy code. The language committees could not tell everyone, "some of
your functions will now disappear, some will change their behavior, and
some will break your programs now". People would simply reject Standard
C++, and keep using the "ARM C++" and its defacto standard.


But that's exactly what the C++ committee did do.


...and you are gainsaying minor details. Of course The Standard broke some
existing code, just as The C Standard broke some existing code.


Well, there's "some" and there's "some". The C Standard bent over
backwards not to break existing code. Even where it did in theory,
in practice the existing code could compile properly with standard
conforming compilers. By contrast, the C++ Standard omitted *every
single* header that had been in use by the community for over a
decade. In their place it introduced a whole new set of headers
with tantalizing similarities to the old stuff, but with pernicious
differences. Some breaks didn't even involve headers or namespace
std -- like new expressions that once returned a null pointer and
now throw an exception. Some "some"s are way bigger than other
"some"s.
So the committee fixed this in one move by putting everything in The
Standard Library into one big namespace. Legacy code that did not
declare this namespace could continue to use their legacy libraries. You
might find your C++ implementation still contains files such as
"iostream.h".


It's nice to think that the C++ committee wisely took a new departure
and made a point of staying out of the way of old library naming
practices, but this was not their goal in adding namespace std and
the new headers. It was the *vendors* who wisely retained the legacy
headers for many years.


Yet if they had not added namespace std, the Standard language would have
been much harder to adopt for billions of lines of legacy code.


I disagree, and I think the evidence supports my position. The vast
majority of new names are in headers that older code would never
have included. The "revised" headers such as <iostream> and <new>
hew closely to past practice. And if you don't want to add several
billion "std::"s to your old code, you have to use the omnibus
"using namespace std" and risk about as many ambiguities as if
the library stayed in the global namespace. Where's the savings?
So it's the
same difference, and it's an adequate way to explain the namespace std
system to a newbie.


It's *not* the same (see above), and while it's a convenient
bedtime story for the kids, it's about as real as Santa Claus.
(Worse, code can also mix-and-match legacy and standard code. The less
said about that the better.)


Maybe, but quite a lot *had* to be said about it, by those of us who had
to support customers through a decade of transition. You will *still*
see regular postings on these newsgroups along the lines of, "I included
<string>, so why isn't class string defined?"


That's not mix-and-match.


No it isn't. I should have used the example, "I've included <iostream.h>
and <string>, so why is my program failing to compile (or link)
properly?" I've seen three references to <iostream.h> in newsgroup
questions just this past week, along with about as many missing
std:: problems.
So, if you need strings or "STL" containers, import their namespace.
This is a very minor detail of well-structured code.


I agree that importing the entire std namespace is often the best way
to repair the damage, but I'm in a tiny minority.


I tried to say "import them from their namespace".


Okay, but even if you import names one at a time from namespace
std, you still run the risk of colliding with names undreamed
of fifteen years ago. Not a big savings.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
May 10 '06 #12
"Earl Purple" <ea********@gmail.com> wrote in message
news:11*********************@v46g2000cwv.googlegro ups.com...
P.J. Plauger wrote:

It would have been far better to leave the Standard C++ library in
the global namespace, where it was born and grew up. You can still
use namespaces to protect your own code, and that is indeed good
style. But nobody seems to teach that.
But then you are assuming that everyone will have to learn the whole of
the standard library to know what is in it to avoid nameclashes.


Nope. Most new names are templates defined in brand new headers.
There's a theoretical risk that <iostream> will drag in <valarray>,
just as there's a theoretical risk that atan2 will drag in strtok.
But in the real world of both Standard C and Standard C++, you can
largely ignore what you don't use in the library.
You should be able to learn a subset of the language and use it. Most
of us do. I don't use <valarray>, rarely if ever use <locale>, don't
use any of the time-formatting stuff...


Right. And putting everything in namespace std neither helps nor
hinders such subsetting. But namespace std sure as hell hinders
a) upgrading existing code and b) teaching newbies. Where's the
net benefit?

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
May 10 '06 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: John Ratliff | last post by:
Let's say I had a program which uses some constants. Would it be "better" to declare them like this: #ifndef __MY_HDR_FILE #define __MY_HDR_FILE #define STRING_CONST "some string..." #define...
97
by: s | last post by:
Can I do this: #define MYSTRING "ABC" .. .. .. char mychar = MYSTRING; .. .. ..
10
by: lallous | last post by:
Hello I noticed that when I use #define inside a namespace then this #define only works when prefixed with the namespace name. Is this behaviour standard or just compiler specific? I use...
2
by: puzzlecracker | last post by:
after reading some of the post I found out something rather radical to my previous understanding: that when you do #include<iostream> #include<string> #include<vector> etc compiler puts...
6
by: clinton__bill | last post by:
Hi, I usually use "using namespace <namespace_name>" to reference a namespace. Today I run across a code, in its header file it has this, namespace SP1{ class C1; } While SP1::C1 is a...
4
by: oliver.lin | last post by:
In my simple test code, I tried to define my constructor outside of the class declaration headr file. The header file: file_handler.h ============================================================...
2
by: psundara | last post by:
Hi, I'm facing a peculiar problem of finding a way to interpret header information in a smart way. I have this header file that is shared by many users, which contains, among things, a few...
4
by: yuliy | last post by:
Hello gurus, I stuck in following: how can I do forward declaration if the forward declared class is in some namespace? something like // header class std::string; // approach#1
7
by: beachdog | last post by:
I'm using Visual Studio 2005/C# to build a web client. The web server is something I've written in a different framework, which does not support generating wsdl, so I have hand-built a wsdl file,...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.