I have a fairly large hierarchy of classes derived from a base class Entity. I would like to group these classes into a separate namespace. Currently, this looks like the following:
namespace Entity {
class Entity {
//...
};
class A : public Entity { // Instead of AEntity from before.
//...
};
class B : public Entity { // Instead of BEntity from before.
//...
};
}
int main() {
// Example usage:
Entity::Entity *entity = new Entity::B();
delete entity;
}
Having to write Entity::Entity is a bit unfortunate, so I'm wondering if this is a good idea? Adding using namespace Entity or typedef Entity::Entity Entity in the global namespace doesn't work (as that would conflict with namespace Entity). They could be added within main though...
Should I avoid naming the namespace the same as the base class within it? Or is this common practice?
Should I avoid naming the namespace the same as the base class within it?
I would. As well as the conflict you point out, it makes it awkward to refer to the namespace from within itself (sometimes necessary when names at namespace scope are hidden within a nested scope). Neither issue is particularly serious, but why make life harder than necessary?
You might call the namespace Entities, since it contains multiple entity types; and/or perhaps call the base class Base, since the namespace completes the description of what it's the base of.
I tend to used different naming conventions for namespaces (lower_case) and classes (Capitalised), but that might not suit your aesthetics or arbitrary corporate dictats.
Related
I remember being told that C++ classes have their own namespaces, and that the class name could be used as a namespace for scope resolution, like this:
// Example.h
class Example {
void Private();
public:
void Public();
}
and, later in a manner similar to this:
// Example.cpp
#include "Example.h"
using /*namespace*/ Example;
void Private() {}
void Public() {}
instead of:
// Example.cpp
#include "Example.h"
void Example::Private() {}
void Example::Public() {}
but I couldn't find neither an explanation nor an example of that in my books. A brief Google search was also a dead-end. Is this a real thing?
No, namespaces and classes are different.
However, namespaces and classes both introduce a scope which may be referred to using the scope resolution operator :: .
The using namespace N; declaration can only apply to namespaces. It's not possible to do something similar for a class. You can only do using Example::x; for specific names x inside Example to import them one by one.
When providing the member function body out-of-line, you must write Example::Private(), there is no alternative.
Yes, Every class has its own namespace that everything part of the class declaration belongs to.
You may employ the using directive as you indicate as explained here.
It should be noted that you cannot declare a namespace with the same name as a class as shown here:
namespace fubar
{
class snafu
{
...
};
}
// Cannot do stuff below (ERROR)
namespace fubar::snafu;
{
// this is not valid, once a class always a class
// once a namespace, always a namespace
// a class makes a namespace also but never JUST a namespace
}
Do be careful though. 'Using' too much can play real tricks on you and those who inherit your code.
This is a question that troubles me a for a while, but could not find a the best way to deal with it. I am trying to show this through an example.
I am developing a graphics library with many classes. Some of the classes are "part of" relationship with each other, like these 3 classes:
namespace MyGraphicsLibrary
{
class MatrixStack
{
};
class Transform
{
MatrixStack mMatrixStack;
};
class Renderer
{
Transform mTransform;
};
}
The Renderer class is for users to use, but i did not want them to see Transform, MatrixStack classes when they lookup the MyGraphicsLibrary. The last two classes are only for Renderer class and not for users to use.
Here i am trying to do two things:
Hiding the Transform, MatrixStack classes from users.
Reflect the "part-of" hierarchy of the classes.
I tried the followings to solve this:
The best solution for me would be the private nested-classes, as it would show the user that the nested class is private and also reflects the hierarchy if you simply look at the Renderer class declaration. The following post actually makes me uncertain that is good solution: Pros and cons of using nested C++ classes and enumerations?
I tried to put Transform, MatrixStack into another namespace called Private. So user looking up MyGraphicsLibrary namespace would see Private namespace only covering all classes which are not for the users.
That's good, but there are lot of other classes with the same issue, and i quickly fill the Private namespace with classes which has nothing to do with each other.
Here I could only come up with ugly solutions, like introducing nested namespaces:
namespace MyGraphicsLibrary
{
//private classes belonging to Renderer class
namespace PrivateRenderer
{
class MatrixStack
{
};
class Transform
{
MatrixStack mMatrixStack;
};
}
//public classes for users
class Renderer
{
Transform mTransform;
};
}
Maybe I miss something here, but what do you think which one is the way to go.
Does anybody has a 3rd way?
you can use the PIMPL- (also called opaque pointer) idiom.
with hat you can entirely hide the classes from user the following way:
In your public header (in your include folder):
Renderer.h
class RendererImpl; // forward declaration of internal render structure
//public classes for users
class Renderer
{
public:
Renderer();
~Renderer();
// public interface comes here and delegates all calls to RendererImpl (have to be implemented in cpp)
RendererImpl* renderer; // better use something like QScopedPointer here
};
the cpp:
#include "RendererImpl.h" // your actual renderer that
Renderer::Renderer()
:renderer(new RendererImpl)
{}
Renderer::~Renderer()
{
delete renderer;
}
The implementations may be completely hidden from the API. The headers have to be separated from the real interfaces.
If you want to store Transform as a plain (non-pointer/reference) member, then for the compilation of your public header, its definition should also be visible, because it affects the layout of the container class.
Consequently, the type will be visible wherever you want to use the container class.
You have the following options:
Signal that they are not for public use through naming. Either by putting into a namespace (like detail in boost), or prefixing/suffixing its name.
Use a technique that prevents clients from using that class. Make every member functions private and declare the container class friend. The attorney-client idiom is a more sophisticated way of fine-grained access control.
Store Transform indirectly (pointer or reference), so you do not need its definition in the public header. This is pimpl. A variant of this if the public type is an interface, a base class of the actual Transform implementation.
Unnamed namespace: definitely a bad idea in a header. Unnamed namespaces are like C static: they get a compiler-generated identifier that is guaranteed to be unique to the given translation unit. You will end up with as many distinct Transform types as many places you included its definition.
Use an anonymous namespace:
namespace MyGraphicsLibrary
{
namespace
{
class MatrixStack
{
};
class Transform
{
MatrixStack mMatrixStack;
};
}
class Renderer
{
Transform mTransform;
};
}
I have a namespace in c++ which contains 5 classes. All of them are having public access modifier. Out of these, 2 classes are static classes.
I want to restrict these classes to be visible outside the namespace in which they are declared.
So, like in another namespace, if I import this namespace, then these 2 classes should not be available to use.
There aren't static classes in C++. If by static classes you mean helper classes used by other classes in your code, and are not meant to be used by client code, then you can use unnamed namespace, and define the helper classes inside them.
namespace somespace
{
namespace //it is unnamed namespace
{
class helper
{
//define it here
};
}
class A
{
helper m_helper;
};
}
Boost uses another technique as well. It defines all the helper classes in a namepace called details.
namespace somespace
{
namespace details //it is details namespace
{
class helper
{
//define it here
};
}
class A
{
details::helper m_helper; //use fully-qualified name
};
}
There are 2 possibilities to prevent using classes in c++, first one is to make these classes private and nested inside the class where you go to use them.
class User{
private:
class Internal{};
};
The second possibility is to make the constructor of your class private and declare the friend classes which will be able to use it like:
class Internal{
private:
friend class User;
Internal(){}
public:
//class interface.
};
I would try to put the two static classes in another namespace and make this namespace useable in the implemention files of the other 5 classes.
More ideas possible, if you give minimal example source.
What is namespace used for, in C++?
using namespace std;
Namespace is used to prevent name conflicts.
For example:
namespace foo {
class bar {
//define it
};
}
namespace baz {
class bar {
// define it
};
}
You now have two classes name bar, that are completely different and separate thanks to the namespacing.
The "using namespace" you show is so that you don't have to specify the namespace to use classes within that namespace. ie std::string becomes string.
It's used for preventing name confilct, so you may have two classes with the same name in different namespaces.
Also it's used for categorizing your classes, if you have seen the .net framework, you will see that namespaces are used for categorizing the classes. For example, you may define a namespace for the employee classes, and a namespace for the tasks classes, and both namespaces are within a namespace for the company classes, since a namespace may contain sub namespaces.
The same namespace may exist in different files, so using it may be useful because it will make you able to directly use all the classes in the namespaces in every #included file.
That's what I remember for now.
One could ask, simple pair of curly braces {} are sufficient to resolve name conflict. Still why have a NameSpace. A quick answer as Tamer mentioned above is that with NameSpace we get the ability to open the same scope in another file.
Namespace usually is used to prevent naming conflicts.
So, One place where namespace comes into picture is
class ABC{
// Does something for me.
};
class ABC{
// Does something for you..
};
int main() {
ABC myABC;
return 0;
}
This will give a compilation error as the system will not know which class is to be considered. Here the concept of namespace comes into picture.
namespace My{
class ABC{
// Does something for me.
};
}
namespace Your{
class ABC{
// Does something for you..
};
}
using My::ABC
// We explicitly mention that My ABC is to be used.
int main() {
ABC myABC;
return 0;
}
Code will be much organized with the usage of namespaces.
This question already has answers here:
Why is "using namespace X;" not allowed at class/struct level?
(6 answers)
Closed 5 years ago.
I find that my C++ header files are quite hard to read (and really tedious to type) with all the fully-qualified types (which goes as deep as 4 nested namespaces). This is the question (all the answers give messy alternatives to implementing it, but that's not the question): Is there a strong reason against introducing scoped using-directive in structs and classes in the C++ language (while it's permissible to have scoped using-declaration in functions)?
e.g.
class Foo : public Bar
{
using namespace System;
using namespace System::Network;
using namespace System::Network::Win32::Sockets;
using Bar::MemberFunc; // no conflict with this
// e.g. of how messy my header files are without scoped using-directive
void FooBar(System::Network::Win32::Sockets::Handle handle, System::Network::Win32::Sockets::Error& error /*, more fully-qualified param declarations... */);
};
Since namespace is a keyword, I would've thought it's distinct enough to cause no conflict with the scoped using declaration such as Bar::MemberFunc.
EDIT: Read the question carefully ---> I've bolded it. Reminder: we're not discussing how to improve readability of the example here. Suggesting how scoped using-directive could be implemented (i.e. by means of adding keywords / constructs etc.) in the C++ language is NOT an answer (if you could find an elegant way to implement this using existing C++ language standards, then it would of course be an answer)!
Sometimes I do this to achieve almost the same effect:
namespace detail {
using namespace System;
using namespace System::Network;
using namespace System::Network::Win32::Sockets;
class Foo : public Bar
{
void FooBar(Handle handle, Error& error);
};
}
using detail::Foo;
Given that using declarations at class scope are not inherited, this could work. The name would only be valid inside that class declaration, or inside the declarations of nested classes. But I think it's sort of overloading the concept of a class with an idea that should be larger.
In Java and Python individual files are treated in a special way. You can have import declarations that inject names from other namespaces into the file. These names will (well, not exactly with Python, but it's too complicated to explain here) only be visible within that file.
To me that argues for this sort of ability not being tied to a class declaration, but given a scope of its own instead. This would allow injected names to be used in several class declarations if it made sense, or even in function definitions.
Here is an idea I prefer because it allows these things while still giving you the benefits of a class level using declaration:
using {
// A 'using' block is a sort of way to fence names in. The only names
// that escape the confines of a using block are names that are not
// aliases for other things, not even for things that don't have names
// of their own. These are things like the declarations for new
// classes, enums, structs, global functions or global variables.
// New, non-alias names will be treated as if they were declared in
// the scope in which the 'using' block appeared.
using namespace ::std;
using ::mynamespace::mytype_t;
namespace mn = ::mynamespace;
using ::mynamespace::myfunc;
class AClass {
public:
AClass(const string &st, mytype_t me) : st_(st), me_(me) {
myfunc(&me_);
}
private:
const string st_;
mn::mytype_t me_;
};
// The effects of all typedefs, using declarations, and namespace
// aliases that were introduced at the level of this block go away
// here. typedefs and using declarations inside of nested classes
// or namespace declarations do not go away.
} // end using.
// Legal because AClass is treated as having been declared in this
// scope.
AClass a("Fred", ::mynamespace::mytype_t(5));
// Not legal, alias mn no longer exists.
AClass b("Fred", mn::mytype_t);
// Not legal, the unqualified name myfunc no longer exists.
AClass c("Fred", myfunc(::mynamespace::mytype_t(5));
This is analogous to declaring a block for local variables in a function. But in this case you are declaring a very limited scope in which you will be changing the name lookup rules.
Maybe namespace alias?
namespace MyScope = System::Network::Win32::Sockets;
You can use a typedef inside the class declaration to achieve the same
class Foo : public Bar
{
typedef System::Network::Win32::Sockets::Handle Handle;
typedef System::Network::Win32::Sockets::Error Error;
void FooBar(Handle handle, Error& error);
};
The obvious benefit of namespaces is that they allow you to avoid naming conflicts. However, by introducing an entire namespace into a class declaration, this benefit is voided. It's entirely possible that a function in the System namespace could conflict with your own Bar::MemberFunc function. You even note this in your sample code when you added the comment "no conflict with this".
You obviously don't want to introduce entire namespaces into your class like this:
using namespace System;
using namespace System::Network;
using namespace System::Network::Win32::Sockets;
And you can't add more narrowly scoped using statements like this into a class declaration. Putting these directly into a class declaration is illegal.
using System::Network::Win32::Sockets::Handle;
using System::Network::Win32::Sockets::Error;
What you can do is use the unnamed namespace. So, your header file would look something like this:
namespace {
using System::Network::Win32::Sockets::Handle;
using System::Network::Win32::Sockets::Error;
}
class Foo : public Bar
{
using Bar::MemberFunc;
// clean!
void FooBar(Handle handle, Error& error /*, more declarations*/);
};
This has three distinct advantages.
The contents of entire namespaces are not introduced. This helps to more easily avoid naming conflicts.
You have a list, before your class declaration, of what your class depends upon to work correctly.
Your function declarations are clean.
Please correct me if I'm wrong; I only briefly tested this. Quickly wrote up an example, and it compiled.