Candy Chiu
Candy Chiu

Reputation: 6679

c++ variable visibility

PLEASE READ THE SECOND EDIT FIRST.

I am looking for books or websites that explain in detailed the c/c++ memory management models. One of the things I am trying to understand is:

namespace A {
    SomeClass A;
}

vs

namespace A {
    static SomeClass A;
}

vs

SomeClass A;

vs

static SomeClass A;

Thank you very much.

EDIT: Sorry for the confusion, I mixed the concepts together, and asked the wrong questions.

Upvotes: 0

Views: 644

Answers (2)

ukhardy
ukhardy

Reputation: 2104

Namespaces allow to group entities like classes, objects and functions under a name. This way the global scope can be divided in "sub-scopes", each one with its own name.

You use keyword using to introduce a name from a namespace into the current declarative region.

For example: without using namespace you will write: #include

int main () {
  std::cout << "Hello world!\n";
  return 0;
}

However you can also write: #include using namespace std;

int main () {
  cout << "Hello world!\n";
  return 0;
}

This allows you not to append napespace identifier before every

In C++ static class has no meaning unlike other OOP languages. You can have static data members methods.

Instead you can create:

1.A static method in class

class SomeClass
{
public:  static void myMethod(int x..)
    {
    }
}

2.Create a free function in namespace

namespace A 
{
    void myMethod(int x..)
    {
    }
}

Latter is better suited when you do not need an object. No class no object...

In both cases enclosing a class within namespace allows you to to group entities under a common name.

Upvotes: 1

Xeo
Xeo

Reputation: 131829

First, namespaces are only known until compilation, after that they're non-existant. That said, your first half is no different from your second half in the final program, at least as far as I know. Correct me if I'm wrong please.

Then, if both static SomeClass A and SomeClass A are at global scope (file level), then they're the same too.

Next, if both declarations are inside of a class, struct or function, then the static version will be put into the data segment of the executable too, while the non-static variant will be a normal stack variable.

Again, please, correct me if I'm wrong, but that's it as far as I know it.

Upvotes: 0

Related Questions