0

In a library I am working with some variables are declared like that:

char &ns::x = y;

However, if I do it that way I get the following error: error: no member named 'x' in namespace 'ns'

If I rewrite it, it works:

namespace ns {
    char &x = y;
}

What exactly is the difference? And why is it working within the library?

1
  • Are you sure that ns in that library is a namespace, and not a class name? Commented Sep 25, 2019 at 17:02

3 Answers 3

3

If you’re right and the code from the library is exactly as written, then this implies that elsewhere in this library, you’ll find the following declaration:

namespace ns {
    extern char& x;
}

In other words, x must have already been declared (and not defined!) inside ns.

Sign up to request clarification or add additional context in comments.

Comments

1

The first declaration

char &ns::x = y;

assumes that the name x is already declared in the namespace ns. However this assumption is wrong (in the provided code snippet there is no previous declaration of the variable. Possibly the code snippet is not complete.).

The code snippet can works provided that the variable x is already declared (without its definition) in the namespace ns.

For example

#include <iostream>

namespace ns
{
    extern char &x;
}

char y;
char & ns::x = y;

int main() {
    return 0;
}

In this code snippet

namespace ns {
    char &x = y;
}

there is defined a reference that is initialized by the object y.

3 Comments

So there definitely has to be a declaration of x anywhere? Because I did not find one in any of the cpp and h files.
@ElasticLamb Yes the variable (without its definition, it has a referenced type) shall be already declared.
@VladfromMoscow Yes — crossed wires.
0

The Variable declaration using namespace:

#include <iostream> 
using namespace std; 

// Variable created inside namespace 
namespace first 
{ 
  int val = 500; 
} 
// Global variable 
int val = 100; 
int main() 
{ 
// Local variable 
   int val = 200; 
// These variables can be accessed from 
// outside the namespace using the scope 
// operator :: 
   cout << first::val << '\n';  
   return 0; 
} 

1 Comment

This doesn't answer OP's question.

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.