1

Here's my code:

#ifndef DATE_H_
#define DATE_H_

namespace std {

class Date {
    public:
       Date();
       virtual ~Date();
    };

} /* namespace std */

#endif /* DATE_H_ */

I created class Date for my assignment, and it created the namespace std{......}. I don't know the use of it. why it is not written as usual use namespace std; what is the difference?

2 Answers 2

8

Your code declares your class Date within the namespace std, i.e. your class fully qualified name would be std::Date

A statement

using namepace std;

Will include the namespace std when searching for symbols.

Some additional notes:

  1. The standard explicitly says that adding things to the std namespace can lead to undefined behaviours making it not only a bad practice but outside of the standard. See Adding types to the std namespace for a detailed discussion.
  2. It's not a good practice to use using namespace on a *.h (or anything that get included in multiple files)... because it might have unexpected side-effects with symbols resolved to wrong namespaces.
Sign up to request clarification or add additional context in comments.

2 Comments

It's not just bad practice: it's prohibited.
@LightnessRacesinOrbit Refined the answer with your suggestion.
6

First of all: you shouldn't put anything in the std namespace, ever.

namespace foo
{
  class A {};
}

puts the class A in the namespace foo, so its full name is foo::A.

using namespace foo;

means that you can access all the things that are in foo without using the qualifier foo::.
Note that using namespace is generally frowned upon and can lead to many unexpected problems.
Most importantly, don't write it in headers.

If you say

using namespace foo;

class A{};

A is not inside foo, but in the global namespace.

2 Comments

Technically, you might want to put a specialization of std::swap in the std namespace.
@ChrisDrew I thought that issue had been solved so we didn't need that hack any more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.