Using Namespaces with Classes Created from a Variable

Using namespaces with classes created from a variable

Because strings can be passed around from one namespace to another. That makes name resolution ambiguous at best and easily introduces weird problems.

namespace Foo;

$class = 'Baz';

namespace Bar;

new $class; // what class will be instantiated?

A literal in a certain namespace does not have this problem:

namespace Foo;

new Baz; // can't be moved, it's unequivocally \Foo\Baz

Therefore, all "string class names" are always absolute and need to be written as FQN:

$class = 'Foo\Baz';

(Note: no leading \.)

You can use this as shorthand, sort of equivalent to a self-referential self in classes:

$class = __NAMESPACE__ . '\Baz';

Can functions or variables be stored inside namespaces instead of classes - C#

No. Those things you mention must be inside a class, not a namespace

To try and help clear up any misunderstanding, a namespace is an organizational facility, in the same way that a folder is for organizing files. You can't open a folder in Word and write some text in it, save the text, copy the folder to another machine etc.. You have to do all that in a file, and then put the file in a folder. In the same way all the "stuff" in C# is done in a class (or enum, struct or similar) which is the corollary of a file on a hard disk. Namespaces just serve to group classes and perhaps disambiguate them if they have the same name as another class in a different namespace

namespace with classes and objects in c++

Seems like your professor wants you to understand following things,

  1. Namespaces, what is the purpose of it.
  2. Do not pollute your namespace. (using namespace std;)
  3. Different kind of constructors.

Tried to compile your program. Not sure all your intentions are correct in following successfully compiled solution. Check it.

#include <iostream>
#include <string>

// Do not pollute the global namespace with using namespace.
//using namespace std;
namespace string {

class string {

std::string a; // Assume you need to store a string inside your class.

public:
string() {};

string (const std::string *q ) : a(*q) { }

string (string &r):a(r.a) { }

string (const std::string &_a):a(_a) { }

~string() {}

void show () {
std::cout << a;
}

void change (const std::string &_a) {
a = _a;
}
}; // ~class end
}; //~namespace end

int main () {

// Use full namespace qualified ID everywhere
string::string s1;
string::string s2("Hello");
string::string s3(s2);
s1.show();
s2.show();
s3.show();
s2.change("Java");
s2.show();
s3.show();
}

Do not use this straightaway. Learn following things.

  1. Namespace pollution - using namespace std in headers are bad.
  2. Purpose of namespaces.

How do I add 'using namespace' to a class definition based on the object name?

This design is all kinds of wrong.

using statements are processed at compile-time only. You can't use a using statement dynamically based on data obtained at runtime (ie, the continent name).

data.h is processed at compile-time only, not at runtime. Its values can't be changed dynamically, such as after a census. Changes would require recompiling the project.

I suggest storing all of your values in an external file, database, etc. Then define a struct to hold the relevent values and pass that to the Continent constructor at runtime. For each continent, read its pertinent values from the external file/database, fill a struct with them, and construct a Continent object with that struct as input. Forget trying to store non-const data in namespaces like you are trying to do.

Is initializing variables in a namespace similar to initializing them as a class member?

No.

The terms member, member variables, member functions and methods are commonly used for class (struct) variables and functions only.

Functions in a namespace are just functions in the scope of the namespace, like variables are simply variables in the scope of the namespace.

Besides the differences between namespaces and classes regarding access and other stuff, the most import difference here is that you can create multiple objects of a class which then each hold their data in their member variables, and the methods == member functions work on this data.

Namespace or class with one member?

If you want to have a single instance (i guess you want a single instance, not a single member, as a member is one of the component fields of the class, and as such, your class has two member fields now) you are probably talking about the singleton pattern (a class with only one instance and no means to instantiate another).

Just declare the constructor private or protected, so client code cannot make a second instance of that object. In that case, you can only use instances already generated for client code, and client code cannot get a new instance (by means of new operator or declaring an instance in main() as you do).

class Canvas final {

// Constructor now is private
Canvas(unsigned width = 10, unsigned height = 30);

public:
unsigned outerWidth, outerHeight;

}

I'd recommend you also to declare outerWidth and outerHeight as const if they are to be exposed publicly by the class, so you cannot modify them (making the instance immutable) or declare accessor methods to access those fields and declare a public and static field instance (or theCanvas), as in:

class Canvas final {

// Constructor
Canvas(unsigned width = 10, unsigned height = 30);

public:
unsigned outerWidth, outerHeight;
static Canvas instance; // we have a static instance defined elsewhere

}

you can instantiate it in a .cc file with:

#include <canvas.h>
...
Canvas Canvas::instance; // by default 10 by 10, this is the public available instance declared above.
...

in this way, you can use Canvas::instance everywhere, that will be an instance of your Canvas class. It will be visible from any source that includes the "canvas.h" include file, and not only in your main() routine, as it is in the sample snippet you post.

By the way, there's no much sense in declaring a constructor with parameters if you are only using it once and in your private code. Also no need to declare default parameter values, but you are in your way. You decide.

Note

As it is not fully clear what you are attempting, I could have misunderstood your intentions, so please, don't blame me if this is not what you want, and edit your question to make your target clearer. You have declared outerWidth and outerHeight as non-const and so, they are modifiable by any code that has access to them. It's not clear if you want your instance immutable (not modifiable once it has been instantiated) nor if they have to take their values from some external code.

Create object with variable class name and namespace

while using shorten namespace path in it.

There is no such thing as "short namespace". A namespace or a class is determined by its complete path, starting from the root namespace.

use Com\Core\Service\Impl as Impl;

Impl in the above fragment of code is a class or namespace alias. An alias is resolved at the compile time and it is valid only in the file where it is declared.

It is not possible to use an alias during the runtime. The only way to refer to a class name during runtime is to generate its absolute path (starting from the root namespace).

You already discovered this.

Read more about namespace aliases/importing.



Related Topics



Leave a reply



Submit