Search code examples
c++namespacesglobal-variablesextern

extern variable in namespace c++


I have a question about the extern variable in namespace c++. Here is the .h file of the CBVR class

namespace parameters
{
class CBVR 
{
private:

    std::string database;

public:

    CBVR(void);

    void initialize(const std::string &fileName);
    static void printParameter(const std::string &name,
                               const std::string &value);
};
extern CBVR cbvr;
}

The .cpp file looks like:

parameters::CBVR parameters::cbvr;


using namespace xercesc;

parameters::CBVR::CBVR(void)
{

}

void parameters::CBVR::initialize(const std::string &_fileName)
{

}

void parameters::CBVR::printParameter(const std::string &_name, const std::string &_value)
{
    if (_value.empty())
    {
        cbvr << "  -> " << _name << " = < EMPTY!!! >" << std::endl;
    }
    else
    {
        cbvr << "  -> " << _name << " = \"" << _value << "\"" << std::endl;
    }
}

In the method printParameter, we're using cbvr without any reference to the namespace. parameters::CBVR parameters::cbvr; handles it but I don't understand what it means and why it allows the cbvr variable to be used like this in the class?

EDITED:

I did this but it says: error: undefined reference to parameters::cbvr

//parameters::CBVR parameters::cbvr;
using namespace parameters;
using namespace xercesc;

CBVR::CBVR(void)
{

}

void CBVR::initialize(const std::string &_fileName)
{

}

void CBVR::printParameter(const std::string &_name, const std::string &_value)
{
    if (_value.empty())
    {
        cbvr << "  -> " << _name << " = < EMPTY!!! >" << std::endl;
    }
    else
    {
        cbvr << "  -> " << _name << " = \"" << _value << "\"" << std::endl;
    }
}

so what's the difference?


Solution

  • Within the member function's definition, you're in the scope of the class, which is in turn in the scope of its surrounding namespace. So anything declared in the class or the namespace can be accessed without qualification there.

    Outside the namespace, the unqualified names aren't available, which is why you need the parameters:: qualification in the variable and function definitions.