473,503 Members | 13,028 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Confusion regarding C++ namespace .

9 New Member
Please help me clear my doubts, regarding C++ namespaces.

For what I know, Namespace defines a scope. Members defined inside namespace have that namespace scope.

And An object cannot be accessed outside it's scope.

1. If that is true how are we able to access a namespace member outside the namespace ?
2. Do member of namespace have global scope ?
3. If namespace members do not have global scope they should not have been accessible outside the namespace scope, Am I correct ?

Expand|Select|Wrap|Line Numbers
  1. namespace n {
  2. int i = 10;  // scope limited to n namespace
  3. }
  4.  
  5. int main(){
  6. std::cout << n::i; // ???? how we are able to access i here ???
  7. return 0;
  8. }
Please help me clear my doubts.
Aug 4 '14 #1
9 1347
weaknessforcats
9,208 Recognized Expert Moderator Expert
First, a member of a namespace cannot be accessed outside the namespace.

Expand|Select|Wrap|Line Numbers
  1. nameapace wfc
  2. {
  3.    int x;
  4. }
  5.  
  6. x = 3;  //error! x des not exist
  7.  
  8. wfc::x = 3;  //OK. x is a member of the wfc name space.
The namespace attaches a name (wfc) to the int x to get wfc::x. Just like what would happen if wfc was a struct.
However, wfc is not a struct. (Even more C++ smoke and mirrors).

Now if the wfc namespace is not in the file being compiled, then:

Expand|Select|Wrap|Line Numbers
  1. wfc::x = 3;  //OK. there is a wfc namespace
  2.  
But this:

Expand|Select|Wrap|Line Numbers
  1. x = 3;   //error. x does not exist.
  2.  
But if you tell the compiler that you are using the wfc namespace:

Expand|Select|Wrap|Line Numbers
  1. using namespace wfc;
  2. x = 3;  //OK. x is a member of wfc namespace
If you want to add y to the wfc namespace, you just code:

Expand|Select|Wrap|Line Numbers
  1. namespace wfc
  2. {
  3.    int y;
  4. }
You don't go looking for the namespace wfc declaration. A namespace is not a struct. There is no one place that contains all the wfc members. Things are in the wfc namespace because you say so.

If you want to delete y from the wfc namespace, just delete the above code.

The primary purpose of the code in this reply is to prevent redefinition errors when code written by carbon is merged in with code written by wfc.
Aug 5 '14 #2
carbon
9 New Member
Thanks buddy ;) Ok I got it . There is another doubt that I would like to clear.

Do Namespace names (identifier) have global scope with external linkage ?
Aug 5 '14 #3
weaknessforcats
9,208 Recognized Expert Moderator Expert
Linkage???

Again, a namespace is not a struct or a variable so the namespace has no linkage. However, the members are variables and they have the linkage they are supposed to have based on where they are defined. If you define the namespace members globally, then they have global scope. If the namespace members are declared statically, then those members are static.

Using namespaces is to prevent compile errors when merging various pieces of code. Once I had to use Microsoft sockets and when I added that code to mine I got errors on GROUP. Turns out there is a group of sockets just like in my code there was a group of managers. Took me a month to remove GROUP from my program and name it something else just so the code would compile. Had the code been in C++ using namespaces it would have compiled the first time.

However, the most powerful use of namespaces is the anonymous namespace:

Expand|Select|Wrap|Line Numbers
  1. namespace
  2. {
  3.      int x;
  4. }
The only access to x will be in the file containing the above code. That means that the name "x" is hidden except from the code in this file.

This allows you to write functions in this file to access x and these functions can be called from anywhere else but the name "x" is hidden. This is fundamental data hiding and this is important because the rest of the program does not know how the data is implemented. You can completely redesign the namespace and the code in this file, recompile and relink, and your program has no idea a redesign was implemented. This would not be possible if the name "x" were scattered all over the place.
Aug 5 '14 #4
carbon
9 New Member
@weaknessforcat Thanks.

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <cstdlib>
  3.  
  4. namespace A {
  5.     int a = 10;
  6.     void get_value(){ std::cout << "a = " << a << std::endl; }
  7. }
  8.  
  9. namespace B {
  10.     int b;
  11.     void get_value(){ std::cout << "b =" << b << std::endl; }
  12. }
  13.  
  14. // using namespace A; if used here generate compilation error 
  15. void set_B();
  16.  
  17. int main(){
  18.  
  19.     using namespace A; // if using-directive is used here no compilation error is generated 
  20.     get_value();
  21.     set_B();
  22.  
  23.     system("PAUSE");
  24.     return 0;
  25. }
  26.  
  27. void  set_B(){
  28.     using namespace B;
  29.     b = 15;
  30.     get_value();
  31.  
  32. }
if using-directive using namespace A; is used outside main() then gcc generates a compilation error "call of overloaded 'get_value()' is ambiguous". Which I understand ,as the using namespace A; introduces A::get_value() to the global-namespace and using-directiveusing namespace B; located inside function set_B(), also introduce the B::get_value() function to the global-namespace. Hence the conflict occurs.

What I don't understand is if using namespace A; using-directive statement is put inside main(), program compiles successfully. Why compiler didn't showed any error. Even if we used the using-directive statement inside the main() the A::get_value() was introduced inside the global-namespace which should have caused conflict with the B::get_value().



I'm teaching myself C++ language. There are lots questions that I would like to ask. So should I create new relevant threads or continue with this one ?
Aug 6 '14 #5
weaknessforcats
9,208 Recognized Expert Moderator Expert
The compiler is processing a function. In this case main where you call get_value(). There is no get_value(). f course there is A::get_value() and B::get_value(). BU these are not called in main(). Therefore the call to get_value() is an error. However, you race in and code using namespace A; before the call which causes the compiler to search the A namespace and finds A::get_value() so it calls that.

There is a danger here. If you are using namespace A and there is a get_value() function in the global namespace, then the compiler doesn't know which one to call so your compiles fails in ambiguous call to get_value().

You are supposed to code A::get_value or ::get_value() to remove any ambiguity and this makes the using namespace directive pointless. In fact, the using directive is considered sloppy.

This thread is considered complete if the questions in your original post are answered. Additional questions should be put in new threads.
Aug 7 '14 #6
carbon
9 New Member
Sorry but this doesn't answer my question. I think you didn't get what I'm trying to ask.

using namespace A; if used outside the main() causes "call of overloaded 'get_value()' is ambiguous" compilation error. Where as it doesn't cause any compilation error when used inside the main().

Here two things are to be considered
using namespace A; // inside or outside main()
using namespace B; // inside function set_B()

In both the cases ( using namespace A either outside or inside main() ) get_value() function from A and B namespace are brought into global namespace, in one case it causes compilation error and in other case no error why ?
Aug 7 '14 #7
weaknessforcats
9,208 Recognized Expert Moderator Expert
When using namespace A is inside main(), it applies only to main(). Therefore, the get_value() is the one in A.

When using namespace A outside main(), there is no issue in main(). The get_value called is the one in A. However, when compiling set_B() does the compiler use A::get_value() or B::get_value introduced by the using namespace B inside that function?

This is exactly the sloppy code I referred to in Post #6. The preferred style is to use A::get_value() or B::get_value() as needed because there is no ambiguity possible.

Failing that, the next preferred style is to place the using namespace declaration at the beginning of each function to limit ambiguity to just that function.
Aug 7 '14 #8
carbon
9 New Member
"When using namespace A is inside main(), it applies only to main(). Therefore, the get_value() is the one in A."

But according to cpp standard members will be introduced into the enclosing namespace which in this case is global namespace.

From Cpp 98 standard ..
7.3.4 : A using-directive specifies that the names in the nominated namespace can be used in the scope in which the usingdirective
appears after the using-directive. During unqualified name lookup (3.4.1), the names appear as if they were declared in the nearest enclosing namespace which contains both the using-directive and the nominated namespace. A using-directive does not add any members to the declarative region in which it appears.


PS: How do I quote lines from a previous reply ?
Aug 8 '14 #9
weaknessforcats
9,208 Recognized Expert Moderator Expert
7.3.4 : A using-directive specifies that the names in the nominated namespace can be used in the scope in which the using directive
appears
after the using-directive.
It means scope. A using directive in a scope, like a function, is limited to that scope.

However, if you have inner scopes in that function, the using directive is valid there also because outer scopes enclose inner scopes.

That is why the using directive in the global scope is so bad. It is valid in every scope in the file whether or not it causes ambiguous name resolution.
Aug 8 '14 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

8
3315
by: gg | last post by:
I am confused regarding what the line in the following function does. It seems to work ok. It seems to be creating a new T object using the pointer to an existing T object. But which function is it...
1
974
by: Vivek | last post by:
Can you guys please tell me weather aspnet_wp.exe is managed code or it is unmanaged code.
1
2613
by: archana | last post by:
Hi all, I am having one confusion regarding changing cursor to wait cursor I am providing auto refreshing facility for listview using timer. So what i am doing is when auto refreshing is in...
4
1384
by: archana | last post by:
Hi all, I am having one confusion regarding invoking web method of web service asychronously through windows applicaiton. What i am doing is i am having one long runing web method whose one...
3
1696
by: archana | last post by:
Hi all, I have one confusion regarding threading in windows service which is developed in c#. What i am doing is on 'onstart' event i am starting one thread. In thread procedure i am...
2
3542
by: archana | last post by:
Hi all, I am not clear regarding waitone of manualresetevent. I am invoking webrequest asynchronously with say 5 requests at a time. What i am doing is after invoking request i am calling...
1
1179
by: archana | last post by:
Hi all, Can anyone tell me is tehre any difference between c# and C#.net any help will be truely appreciated.
2
3863
by: archana | last post by:
Hi all, I am having one confusion regarding hashtable. I am having function in which i am passing hashtable as reference. In function i am creating one hashtable which is local to that...
3
1571
by: archana | last post by:
Hi all, I read some where that in 2003 you could not able to install application assemblies in GAC.In Visual Studio 2005 you can even add application assemblies to the GAC .You can install Exe...
0
1094
by: Adi | last post by:
hi everyone.. i am working on a web application in VS 2005.. i recently converted my application from VS2003 to VS2005.. after the conversion.. when i compiled the application i was starting to get...
0
7296
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
7364
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...
1
7017
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
7470
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
5604
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,...
1
5026
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4696
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3186
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
1
751
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.