![]() |
namespace vs struct
Usually when I want global functions in my C++ applications I do like this:
:
namespace ToolAnother more common way to achieve this result is by doing it this way: :
struct ToolSo to my question: Is there a difference between them (have not checked the generated code yet)? Which one should I prefer and why? Thanks for your thoughts! /Klarre |
Well I'm no pro but I'm pretty sure the second one doesn't work. More like
:
struct ToolHope I helped >_> |
Quote:
|
I think namespaces are there to resolve naming conflicts for linker in different parts of the program. For example, if you had a function with declaration "int foo() {}" in one file of your program, you shouldnot be able to have the same thing somewhere else unless its in different namespace. This is vary useful in program organization in large programs. Should be nothing more and nothing less.
|
Assuming all of your functions are static, there is no difference between the two approaches. A name of the struct (or class) is, in this context, a namespace. That is, among other things, why the syntax "Tool::foo();" works for calling Tool::foo() in both cases.
The example given by peaceofpi does not work, as the name of an object is not a namespace. |
I would suggest going with the namespace, from a practical point it means you don't have to declare everything you want to put into 'Tool' at the one point.
Plus, stylistically, I feel the namespace version more clearly expresses your intentions. Could be just me though. |
I would suggest going for the struct as you can do this
Tool a; a.foo(); or something of that effect. You can also go for classes as you can inherit them. (but now you can also inherit them in structs) which can make your expansion easier. But if you won't make variables out of struct, it defeats the purpose and so it's cooler to use Namespace. |
I guess that namespaces and structs are way too different. Most of their differences are in the way you concieve your program and the reusability of the code. You create a namespace when you create your own library or anything like that if you want to prevent nameclashes. You create struct if you have to abstract an object in the real life( because c++ treats structs and unions the same as classes).
|
A namespace defines a scope. All its members are public; forget access specifiers. Unlike a class or a struct, it is open. That is, you can extend it later with more definitions. Also unlike a class or struct, the closing brace does not have a following semicolon.
|
| All times are GMT -5. The time now is 1:27 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC