0

I've got two questions.

Question 1: Can someone provide an example of how to define/redefine a variable in a namespace. I've provided my own guess for you to base an your answer from.

// namespace.hpp
namespace example
{
    static string version;
    static int x;
}

And then in a .cpp how do I redefine those variables?

// namespace.cpp
namespace example
{
    version = "0.1"; // ?????
    x = 0; //???
}

Question 2: How would I attach a permanent class object onto a namespace from the same .hpp file? Something like this:

// namespace.hpp
class Idk
{
    public:
        int doThis();
}

namespace example
{
    Idk idkObject;
}

The code above, when included multiple times (from different files) will replace the object, which will cause compilation errors. Once again, I need a permanent way to attach a object to a namespace its header file.

Honor
  • 63
  • 2
  • 9

2 Answers2

1

Instead of 'static', write 'extern' in the header file and include the data type in the variable definitions in the cpp file.

Lukas Kalinski
  • 2,213
  • 24
  • 26
0

Question 1: You need to specify the type also

// namespace.cpp
namespace example
{
    string version = "0.1"; // ?????
    int x = 0; //???
}

Question 2: You shouldn't create a 'non-static' object in a header file irrespective of the namespace. You should just use static here also or else you should use extern in header file and define the variable inside a cpp file. {Note it's a little different with templatized classes}

// namespace.hpp
class Idk
{
    public:
        int doThis();
}

namespace example
{
    static Idk idkObject;
}

// namespace.cpp
namespace example
{
    Idk idkObject; // Default constructor
}
Sid
  • 29
  • 4
  • 1
    Redefining the variables from question #1 isn't working for me. I have the header namespace define them as static variables. And then the .cpp namespace copied exactly like your code. And it keeps error me saying it's a redefinition. – Honor Mar 22 '14 at 21:08