Can a class be effectively called a namespace?
My impression is: no. A namespace just adds a qualifying name to a function or variable, and you can call the function or variable at any time using the full name:
Code:
#include<iostream>
#include<string>
using namespace std;
namespace Apple
{
int num = 10;
}
int main()
{
cout<<Apple::num<<endl;
return 0;
}
Normally, class functions or variables can only be called by class objects, but a public static function or variable in a class is an exception to that rule, and it is called with a similar syntax as when using a namespace:
Code:
#include<iostream>
#include<string>
using namespace std;
class Apple
{
public:
static int num;
};
int Apple::num = 10; //initialize the static variable
int main()
{
cout<<Apple::num<<endl;
return 0;
}
However, in general static functions and variables seem very different from a function or a variable in a namespace. For instance, a static variable can have a private access specifier, which limits access to the variable--only class objects that call class methods can access the variable.
Code:
#include<iostream>
#include<string>
using namespace std;
class Apple
{
private:
static int num;
public:
void display()
{
cout<<num<<endl;
}
void set_num(int n)
{
num = n;
}
};
int Apple::num = 10; //initialize the static variable
int main()
{
Apple myApple;
myApple.display();
cout<<Apple::num<<endl; //error: access denied
return 0;
}
Variables in namespaces don't have access specifiers.
In addition, every object of a class has a pointer to the static variable, so when you change a static variable it is reflected in all the objects of the class:
Code:
#include<iostream>
#include<string>
using namespace std;
class Apple
{
public:
static int num;
};
int Apple::num = 10; //initialize the static variable
int main()
{
cout<<Apple::num<<endl;
Apple apple1, apple2;
cout<<apple1.num<<" "<<apple2.num<<endl;
Apple::num = 40;
cout<<apple1.num<<" "<<apple2.num<<endl;
return 0;
}
A namespace variable has no comparable functionality.
Namespaces allow you to declare using directives so you can forgo having to use the qualifying namespace name, which you can't do with a static class variable or function.
edit:
Originally Posted by
Prelude
>Can a class be effectively called a namespace?
Yes, more or less.
Uh, oh.
Originally Posted by
Prelude
Do not post below this line
---------------------------------
For senior member use only
...wish I had been paying attention.