none
Namespace vs. Struct

    Domanda

  • Hi,

    I just created a struct in my program.  The purpose was to organize my functions and variables better.  So the functions and variables that were associated with different tasks went in different structures.

    But I also just read about the "Namespace" concept and this seems to do the same thing I want.  I can organize functions and variables by their use and put them in different namespaces.  That will organize the program better.

    My question is, why have a struct when you can just use a namespace?

    Thanks

    martedì 13 marzo 2012 14:19

Risposte

  • So you are in favour of increasing code size to create another instance of an object?

    Simplicity like

    struct mystruct
    {
        int a;
        int b;
    };
    
    mystruct ma;
    mystruct mb;

    to get two instances of that structure rather than creating two completely seperate namespaces. Also you can do structure assignment and (with some operator overloading) comparisons too.

    ma = mb; //works

    This doesn't work on namespaces.

    For the memory issues, think of it this way, each namespace you create adds code, this increases the size of the executable. Each variable you add to a namespace is a global variable, so it adds to the executables size.


    This is a signature

    Any samples given are not meant to have error checking or show best practices. They are meant to just illustrate a point. I may also give inefficient code or introduce some problems to discourage copy/paste coding. This is because the major point of my posts is to aid in the learning process.

    Do you want Visual Studio 11 Express to be freely installable on Windows 7 and able to write regular C++ applications? Please vote for this.

    • Contrassegnato come risposta Jeffs_Programs martedì 13 marzo 2012 18:09
    martedì 13 marzo 2012 16:08

Tutte le risposte

  • A struct is a datatype, a namespace isn't.

    namespaces are used to organize your names within your program.

    struct are used to define your own datatypes. These are totally different things!

    martedì 13 marzo 2012 14:23
  • Namespace is just a declerative region for your function or variable etc . With the help of struct and class you can define your own data type and structure always has a valid size  .But with namespace it is just about the scope inside in other function and while namespace are a logical entity. size of a namespace does not mean anything.

    Thanks


    Rupesh Shukla

    martedì 13 marzo 2012 14:49
  • I don't think what you are saying is clear.

    If I organize names of variables and functions in a program, how is this different then defining datatypes.  I don't think it is different.

    Struct Names{... define names}

    Names.variable = 1;

    Is no different then creating a namespace Names

    Names::variable = 1.

    How is this different, you make a definition in both cases.

    martedì 13 marzo 2012 14:59
  • Struct Names{... define names}

    Names.variable = 1;

    There is a huge difference this is a struct and has a valid type .you can create a object of your struct and you can get size of your struct as i mentioned above . dot operator tells here that variable is a member of your newly created datatype with help of struct once creation is done , forget about deep detailing if i have to create 10 different element of Names i am going to perform same operation as i do with primitive datatype . But this is not true with namespace.

    Names::variable = 1.

    :: this is a scope resolution operator which basically tells use variable from declerative region Names .In your case , the variable is a  normal variable declared within a namespace called Names. In order to access these variables from outside the Names namespace we have to use the scope operator ::. But as already mentioned this now a type of so you can't create a object of your namespace you only can inform to compiler use this but can't  say

    Names myname;

    and in last as i mentioned they are logical entity .So size doesn't mean anything you can't say size of Names etc. if still any problem please let me know.

    Thanks



    Rupesh Shukla


    martedì 13 marzo 2012 15:18
  • Names myname; \\creates an instance of the stucture

    You can just copy the namespace and then you have a new namespace.  Just make another copy and call it myname, or yourname, or hisname.  That is the same as creating another object of the structure isn't it.


    In the end it looks like you have accomplished the same thing.


    Also, it is not clear what you are trying to accomplish by creating a structure.  Namespaces organize your code, structures seem to make it more complicated with little added value.
    martedì 13 marzo 2012 15:47
  • Simple.

    struct mystruct
    {
        int a;
    };
    
    mystruct *ms = new mystruct;

    Try doing that with a namespace. Namespaces are there to organise things so you can get rid of naming conflicts, structs puts all of this into one block of memory. The variables you create in a namespace are still global variables that take up space in the executables data segments, but the structures aren't they are either stack or heap variables that you can pass around in blocks like this.

    Structures are also types, namespaces aren't. So you can pass structures as parameters, namespaces can't be used that way.


    This is a signature

    Any samples given are not meant to have error checking or show best practices. They are meant to just illustrate a point. I may also give inefficient code or introduce some problems to discourage copy/paste coding. This is because the major point of my posts is to aid in the learning process.

    Do you want Visual Studio 11 Express to be freely installable on Windows 7 and able to write regular C++ applications? Please vote for this.


    • Modificato Crescens2k martedì 13 marzo 2012 15:54
    martedì 13 marzo 2012 15:51
  • Crescent,

    You can do the same thing by creating another namespace.

    mystruct *ms = new mystruct;

    But you also seem to be in favor of structs because of memory issues, what are those exactly?

    martedì 13 marzo 2012 15:59
  • So you are in favour of increasing code size to create another instance of an object?

    Simplicity like

    struct mystruct
    {
        int a;
        int b;
    };
    
    mystruct ma;
    mystruct mb;

    to get two instances of that structure rather than creating two completely seperate namespaces. Also you can do structure assignment and (with some operator overloading) comparisons too.

    ma = mb; //works

    This doesn't work on namespaces.

    For the memory issues, think of it this way, each namespace you create adds code, this increases the size of the executable. Each variable you add to a namespace is a global variable, so it adds to the executables size.


    This is a signature

    Any samples given are not meant to have error checking or show best practices. They are meant to just illustrate a point. I may also give inefficient code or introduce some problems to discourage copy/paste coding. This is because the major point of my posts is to aid in the learning process.

    Do you want Visual Studio 11 Express to be freely installable on Windows 7 and able to write regular C++ applications? Please vote for this.

    • Contrassegnato come risposta Jeffs_Programs martedì 13 marzo 2012 18:09
    martedì 13 marzo 2012 16:08
  • Hi,
     
    I just created a struct in my program. The purpose was to organize my functions and variables better. So the functions and variables that were associated with different tasks went in different structures.
     
    But I also just read about the "Namespace" concept and this seems to do the same thing I want. I can organize functions and variables by their use and put them in different namespaces. That will organize the program better.
     
    My question is, why have a struct when you can just use a namespace?
    A struct (or class) that has only static data and methods is not so different from a namespace. But with a struct that has non-static data, you can create different objects with different data.
     
    In some languages (e.g. C# or Java) every function must be a class method, so you will find purely static classes. This is not so common in C++, because non-class functions can be placed in a namespace, as you have discovered.
     

    David Wilkinson | Visual C++ MVP
    martedì 13 marzo 2012 17:11
  • If I create another instance of the structure would this slow down the program and add to the memory overhead?

    Since I am no reusing the variables/functions I don't need to take advantage of a structures reusability.  But you mention an advantage of saving memory without using global variables that seems woth looking into.

    martedì 13 marzo 2012 17:45
  • Also, it is not clear what you are trying to accomplish by creating a structure.  Namespaces organize your code, structures seem to make it more complicated with little added value.

    Okay a very simply answer what if you want to store information about a student or all the student in the class. like his age ,name address ,phone no etc. If you are going to use structure here

    like

     struct record

    {

     char *                 name;

    int                     age;

     int                   phone ;

        int                 roll ;

    };

    Now you can create n no of object of this structure . and can assign the value now if i ask hey can you provide me the information of 17th student you simply can say object[17] and can get all the information about the student . But you can't do same with namespace .And here is the thing if you want to do with name space you have to perform lots of array operation etc like a array for keeping all names and one  for age etc.

    So think about record and a single entity if you just want to perform operation use namespace struct or simple variable doesn't give any impact but when you want to perform operation on records you need a data structure which is easy to access so this is the mazor difference.

    Thanks


    Rupesh Shukla


    martedì 13 marzo 2012 17:53
  • No Creating instance doesn't mean memory overhead .And even in case of namespace what i mean to say take a example of iostream file if i just want to use a particular region of namespace i can simply say

    using std::count or using std::cin instead of adding entire namespace to my code . So this all depend how you use it in your program . But the basic thing is namespace is a declerative region for your data object and class and structure are used to perfrom operation on those object.

    Thanks


    Rupesh Shukla

    martedì 13 marzo 2012 18:09
  • So you are in favour of increasing code size to create another instance of an object?

    Simplicity like

    struct mystruct
    {
        int a;
        int b;
    };
    
    mystruct ma;
    mystruct mb;

    to get two instances of that structure rather than creating two completely seperate namespaces. Also you can do structure assignment and (with some operator overloading) comparisons too.

    ma = mb; //works

    This doesn't work on namespaces.

    It is absolutely fine with namespace to without creating another namespace if it is just assignment.

    namespace t
    {
    	int a =10;
    	int b=30;
    }
    using namespace t;
    int _tmain(int argc, _TCHAR* argv[])
    {
    	namespace d =t;	
    	std::cout<<d::a;
    	return 0;
    }
    Thanks

    Rupesh Shukla

    martedì 13 marzo 2012 18:22
  • Well, with the way VC implements global variables, it all goes into the executable file so it increases the size of the executable. Whats more, since they are global, the namespaces and these variables in the namespace are always going to be in memory.

    Structures on the other hand will either go onto the stack or heap. So they will only take up memory while they are in scope and will get cleaned up after wards.

    So as an example:

    namespace a
    {
        int a;
        int b;
    }
    
    struct b
    {
        int a;
        int b;
    };
    
    //namespace a is always going to be taking up memory
    
    int main()
    {
        b myvar1; //b gets allocated here
        {
            b myvar2; //another b gets allocated here, myvar1 is still allocated
        }//myvar2 gets deallocated here so it is now no longer using up memory
    }//myvar1 gets deallocated here so it is no longer using up memory

    so depending on usage, structures will use up less memory than global variables in namespaces.

    As for whether it slows down the program, you will most likely see no to little difference. The compiler usually optimises it so that any space that would be used for the structure gets allocated at the start of the function anyway. Or at the most, it would be a single assembly instruction so namespaces give nothing worth the effort. As for memory overhead, no, nowhere near as much as using namespaces and globals. In the small sample above, the namespace is using 8 bytes constantly throughout the program, but both of the structures will only use memory when needed, so by the end of main 0 bytes are used for the structures.

    The more namespaces you add the more overhead they need, but for structures they will have the code overhead like namespaces, but for memory usage it will be 0 initially and then the memory will be allocated either on the stack or on the heap as and when you need it and then removed when you no longer need it.

    The only way you can ever get structures to use a constant memory overhead is if you allocate them globally too.

    This post is written under the assumption that the struct is a PoD type.


    This is a signature

    Any samples given are not meant to have error checking or show best practices. They are meant to just illustrate a point. I may also give inefficient code or introduce some problems to discourage copy/paste coding. This is because the major point of my posts is to aid in the learning process.

    Do you want Visual Studio 11 Express to be freely installable on Windows 7 and able to write regular C++ applications? Please vote for this.

    • Modificato Crescens2k martedì 13 marzo 2012 18:27
    martedì 13 marzo 2012 18:23
  • That just aliases the original namespace that doesn't copy the data from t into d. Whats more, that has to be done when the namespace is being defined, but it can't be done at some arbritary point afterwards. Another thing to remember is that with structures, both structures are distinct. What you did  makes both namespaces point at the same one. So

    #include <tchar.h>
    #include <iostream>
    
    namespace mynamespace
    {
    	int a = 5;
    }
    
    int _tmain()
    {
    	namespace mynamespace2 = mynamespace;
    
    	mynamespace2::a = 1;
    
    	std::cout << mynamespace::a << std::endl;
    
    	return 0;
    }

    will print out 1 where

    #include <tchar.h>
    #include <iostream>
    
    struct mystruct
    {
    	int a;
    };
    
    int _tmain()
    {
    	mystruct a = {5};
    	mystruct b = a;
    
    	b.a = 1;
    
    	std::cout << a.a << std::endl;
    
    	return 0;
    }

    will print out 5.


    This is a signature

    Any samples given are not meant to have error checking or show best practices. They are meant to just illustrate a point. I may also give inefficient code or introduce some problems to discourage copy/paste coding. This is because the major point of my posts is to aid in the learning process.

    Do you want Visual Studio 11 Express to be freely installable on Windows 7 and able to write regular C++ applications? Please vote for this.

    martedì 13 marzo 2012 18:50
  • This is what i mentioned in my last post if it is just assignment which was reply of your last post.

    Thanks


    Rupesh Shukla

    martedì 13 marzo 2012 19:13
  • The point is though, this isn't assignment. This is aliasing.

    With assignment, you assign the contents of one thing to another. This requires to distinct objects to start off with and they stay two distinct objects. The use of the equals in the namespace decleration is to say that this is an alias for another namespace. The namespaces are not distinct objects at all. In fact, this is better seen as a typedef or as a reference rather than an assignment.

    As code, namespace aliasing could be better seen as:

    #include <tchar.h>
    #include <iostream>
    
    struct mystruct
    {
    	int a;
    };
    
    int _tmain()
    {
    	mystruct a = {5};
    	mystruct &b = a;
    
    	b.a = 1;
    
    	std::cout << a.a << std::endl;
    
    	return 0;
    }

    which is clearly not the same. With this, the assignment is not for the contents of a, but rather the address of a.


    This is a signature

    Any samples given are not meant to have error checking or show best practices. They are meant to just illustrate a point. I may also give inefficient code or introduce some problems to discourage copy/paste coding. This is because the major point of my posts is to aid in the learning process.

    Do you want Visual Studio 11 Express to be freely installable on Windows 7 and able to write regular C++ applications? Please vote for this.

    martedì 13 marzo 2012 19:24
  • So if I create an instance of the structure

    sturct NewStruct{...}

    NewStruct new

    new...

    By creating "new" an instance of the structure this does not create any overhead?

    martedì 13 marzo 2012 19:31
  • Thats good info Dave.

    I tried putting the functions in a struct and a namespace.  I kind of prefer the way the struct is displayed on the properties panel so I might go with a struct because the organization is nice.  But a namespace gives me most of the same organization layout.

    martedì 13 marzo 2012 20:08