Structures? *brain melts*

This is a discussion on Structures? *brain melts* within the C++ Programming forums, part of the General Programming Boards category; Yes, there are reasons to provide constructors a lot of the time. There is not always a reason, however. Additionally, ...

  1. #31
    mustang benny bennyandthejets's Avatar
    Join Date
    Jul 2002
    Posts
    1,401
    Yes, there are reasons to provide constructors a lot of the time. There is not always a reason, however. Additionally, if you want to get rid of the copy semantics, and default constructor, you must declare them away:


    code:--------------------------------------------------------------------------------
    class X
    {
    public:
    // Whatever constructors you want.
    private:
    // Declare away!
    X();
    X(const X&);
    X& operator=(const X&);
    };
    --------------------------------------------------------------------------------
    What does that do? Wouldn't it mean there are no more constructors?

    Okay, explaining this as simple as I can... A structure, to me, is a scope enclosed with curly braces that contains variable initializations, for example:


    code:--------------------------------------------------------------------------------
    struct myvariables
    {
    int variable1
    int variable2
    }
    --------------------------------------------------------------------------------


    and there has to be some way to call on one of these variables that are contained inside of the above "scope" right? So, I figure you would put the name of the structure, then a period, and the name of the variable inside of the structure that you want to change, like so:

    myvariables.variable1=3

    To me, this would say "Look inside of structure 'myvariables' and find 'variable1' then set it to 3!"
    A structure is a user-defined type that contains declarations, definitions, and initializations. Note that your example above contains 'declarations' not 'intializations'.

    You cannot say myvariables.variable1=3. myvariables is not an object, it is a type. You can create an object based on that type, ie:
    Code:
    myvariables foobar;
    Then assign things:
    Code:
    foobar.variable1=3;
    You have to understand though that there is not a 'myvariables' object in memory before you create an instance of it. It is like a template to design an object with.
    benforbes@optusnet.com.au
    Microsoft Visual Studio .NET 2003 Enterprise Architect
    Windows XP Pro

    Code Tags
    Programming FAQ
    Tutorials

  2. #32
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,598
    http://www.informit.com/isapi/guide~...de/content.asp


    Herein lies the difference. I just never instantiate classes w/o using new. But if you wish to create them in another fashion that
    is up to you. So your compiler won't shout at you.

    From Borland help file

    Syntax:

    <::> new <new-args> type-name <(initializer)>
    <::> new <new-args> (type-name) <(initializer)>

    Description

    The new operator offer dynamic storage allocation, similar but superior to the standard library function malloc. The new operator must always be supplied with a data type in place of type-name. Items surrounded by angle brackets are optional. The optional arguments can be as follows:

    :: operator, invokes the global version of new.
    new-args can be used to supply additional arguments to new. You can use this syntax only if you have have an overloaded version of new that matches the optional arguments.
    initializer, if present is used to initialize the allocation.

    A request for non-array allocation uses the appropriate operator new() function. Any request for array allocation will call the appropriate operator new[]() function. Selection of operator is done as follows:

    By default, operator new[]() calls operator new()
    If a class Type has an overloaded version of operator new[](), arrays of Type will be allocated using Type::operator new[]()
    If a class Type has an overloaded version of new, and no overloaded version of the array allocator operator new[](), arrays of Type will be allocated using Type::operator new()
    Memory for a non-array object of Type is allocated using Type::operator new()
    If none of the above cases apply, the global ::operator new() is used

    Note: Arrays of classes require the default constructor.

    new tries to create an object of type Type by allocating (if possible) sizeof(Type) bytes in free store (also called the heap). new calculates the size of Type without the need for an explicit sizeof operator. Further, the pointer returned is of the correct type, "pointer to Type," without the need for explicit casting. The storage duration of the new object is from the point of creation until the operator delete destroys it by deallocating its memory, or until the end of the program.
    If successful, new returns a pointer to the new object. By default, an allocation failure (such as insufficient or fragmented heap memory) results in the predefined exception xalloc being thrown. Your program should always be prepared to catch the xalloc exception before trying to access the new object (unless you use a new-handler).

    A request for allocation of 0 bytes returns a non-null pointer. Repeated requests for zero-size allocations return distinct, non-null pointers.

    Handling Errors for the new Operator

    You can define a function to be called if the new operator fails. To tell the new operator about the new-handler function, use set_new_handler and supply a pointer to the new-handler. If you want new to return null on failure, you must use set_new_handler(0).
    New is just more versatile.

  3. #33
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    What your thinking of is a namespace.

    Code:
    // For example
    namespace a
    {
      int b;
      char c;
    }
    
    ... later on in some function ...
    a::b = 4;
    a::c = 'f';
    A structure is a template for a type. For example, you can't say:

    int = 3;

    That is, you can't assign anything to int, but you can assign things to an int.

    int x = 4;

    The example of the Cat, Cat is like int.
    Cat Tintin; // Tintin is a variable of type Cat.

    You can create many instances of a class, and they all have their own separate memory. For example, if you were creating a database of cats, you would not want to create numerous structures of type Cat.

    class Cat1 { ... };
    class Cat2 { ... };
    ad infinitum

    Instead, you'd like a template of a cat. What properties do all cats have? Weight, color, etc. Classes are just that.

    Cat A;
    Cat B;
    A.Weight = 20;
    B.Weight = 15;

    What you have is two Cats (that is structures having the same properties with different values for those properties).
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  4. #34
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,598
    Just create it on the stack.


    Ewwww. Sorry being heavily involved in assembly programming that statement just makes me cringe.



    Anyways to stick with the example and keep it simple do what they are saying.

    As has been said you must create an object of the type you have declared before you can use it. The declaration is just a template as to what the object will look like.

    But using template in that sentence also makes me cringe....



    So benny if u don't use new you are creating the object on the stack and if you use malloc or new you are creating it dynamically in memory.

  5. #35
    mustang benny bennyandthejets's Avatar
    Join Date
    Jul 2002
    Posts
    1,401
    Bubba, that site contains a nice use of dynamic allocation with derived classes, but at the moment is probably not very useful for TheDoomMaster. I see your point though.

    A word of advice: let's be nice and not confuse n00bs okay? Keep it simple.

    So benny if u don't use new you are creating the object on the stack and if you use malloc or new you are creating it dynamically in memory.
    I'm not a n00b Bubba. I understand stack vs dynamic allocation.
    benforbes@optusnet.com.au
    Microsoft Visual Studio .NET 2003 Enterprise Architect
    Windows XP Pro

    Code Tags
    Programming FAQ
    Tutorials

  6. #36
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    What does that do? Wouldn't it mean there are no more constructors?
    It just gets rid of those two constructors and the assignment operator. You can define as many other constructors as you want (or you can define none, but then you need a static build function, or a friend which creates instances of the class).

    Bubba, your point about polymorphism is a good one, but it fails. You do need 'new' if you want to do something like this:

    Shape* a = new Square;

    From my experience, this particular situation is rare except for in demonstrations. What is more often the case is that you want to pass any type of Shape to a function. This can be done in a couple ways without dynamic allocation:

    Code:
    // Assumes Shape as defined in the link exists.
    
    void f1(Shape& s)
    {
        s.Draw();
    }
    
    void f2(Shape* s)
    {
        s->Draw();
    }
    
    void f3( )
    {
        Square x;
        Triangle y;
    
        f1(x);
        f1(y);
        
        f2(&x);
        f2(&y);
    }
    Both work as advertised, and there is no dynamic allocation. There are clearly many reasons to allocate things dynamically, but there is no reason to needlessly do so.
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  7. #37
    Registered User MrDoomMaster's Avatar
    Join Date
    Oct 2003
    Posts
    53
    OH! OMG! I GET IT!

    So, structures are kind of like three dimensional arrays?

    you can create your own types that have really no other purpose but to organize information for database-like structure in your code?

    I think I get it now, Lemme try to type in some code off the top of my head:

    Code:
    //My lame *** programming skills
    
    #include <iostream> // is it absolutely necessary to use the <>'s?
    using namespace std;
    
    main()
    {
       struct computers       //not sure if I needed a ; here
       {
          int speed;
          int ram;
       };                      // why do you need a ; after the }?
    
    computers gateway;    // this would create variable 'gateway' of type 'computers'?
    
    gateway.speed=133;
    gateway.ram=128;             //these set properties to gateway?
    return 0;
    }

    so, how did I do? I hope I understand it! I realize I may have used some reserved words, I'm not too sure. But work with me!

    Now, I remember you guys using "public:" and "private:"... what's all of that about?


    Also, just a quick question on syntax... what if I try to do this, based on the above code I have typed:

    gateway.weight=10

    As you know, I never initialized "weight" inside of my structure named "computers". Details on this type of mistake/error would be helpful! just to be aware of what the compiler will do!

    Thanks everyone!
    --MrDoomMaster
    The kind of DooM that makes the MooD

  8. #38
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Ewwww. Sorry being heavily involved in assembly programming that statement just makes me cringe.

    Hmm.. not being an assembly programmer, it doesn't conjure nasty images for me... Anyways, I trust the nice optimizing compilers... mostly.

    But using template in that sentence also makes me cringe....
    Me too, but I couldn't think of a better word.
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  9. #39
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    The 3d arrays analogy doesn't quite make sense to me, but your code looks good.

    You can even have member functions of structures, but that can wait 'til later. It seems like you understand the basic concept.

    If you never told it that the variable 'weight' exists, the compiler will say something to the effect of "Undeclared identifier" and stop compiling.
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  10. #40
    mustang benny bennyandthejets's Avatar
    Join Date
    Jul 2002
    Posts
    1,401
    so, how did I do?
    You're nearly there. structs should be declared globally, outside any functions.
    Code:
    struct computers
    {
      int foo;
      int bar;
    };
    
    int main()
    {
    return 0;
    }
    Note that the function main() must be declared with the type 'int'.

    So, structures are kind of like three dimensional arrays?
    Erg....... Only so because they both store a lot of data. However, I wouldn't call them analgous.
    benforbes@optusnet.com.au
    Microsoft Visual Studio .NET 2003 Enterprise Architect
    Windows XP Pro

    Code Tags
    Programming FAQ
    Tutorials

  11. #41
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,598
    Well anyways now that the interested party is confused thanks to our ranting and raving....next question MrDoomMaster and we will see if we can't confuse you more.



    Just kidding man...really..we don't mind helping. We've all been there scratching our heads before....and still do.


    edit: Man this post is growing exponentially. Can't keep up.


    Looks like you got it man....but the 3D analogy lost me...so let's just forget you made it and move on.
    Last edited by VirtualAce; 11-01-2003 at 05:29 PM.

  12. #42
    mustang benny bennyandthejets's Avatar
    Join Date
    Jul 2002
    Posts
    1,401
    is it absolutely necessary to use the <>'s?
    Yes. The <>s tell the compiler to look for the file in all the common places, like the compilers own stash of include files. Using quotes, ie, #include "myheader.h", tells the compiler to look in the project's working directory, ie, the same directory where the source files are.
    benforbes@optusnet.com.au
    Microsoft Visual Studio .NET 2003 Enterprise Architect
    Windows XP Pro

    Code Tags
    Programming FAQ
    Tutorials

  13. #43
    Registered User MrDoomMaster's Avatar
    Join Date
    Oct 2003
    Posts
    53
    Originally posted by Zach L.
    The 3d arrays analogy doesn't quite make sense to me, but your code looks good.

    You can even have member functions of structures, but that can wait 'til later. It seems like you understand the basic concept.

    If you never told it that the variable 'weight' exists, the compiler will say something to the effect of "Undeclared identifier" and stop compiling.

    by 3d array, use this for example:

    Computers >> Gateway >> speed

    this would be, 3darray[computers][gateway][speed]

    kinda see now? anyway, it was just a stupid comparison.

    NOW, to understand the point of POINTERS!

    Pointers don't sound too tough, I think I might be onto understanding them, but there's still a few little things that don't make sense...

    by default, when you declare a variable of type int, it just selects a random available range of memory to place its value in, right? So, therefore a pointer would be more static?

    Pointers = Static (doesn't change)
    Variables = Dynamic? (changes)

    I REALLY don't understand memory addresses right now, that seems like the deepest darkest reaches of programming for me right now, I'm still digging to that depth. But for now, am I even close? Use a pointer to always point to a static range of memory?
    --MrDoomMaster
    The kind of DooM that makes the MooD

  14. #44
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,598
    What? When did we start talking about headers? Now I think I'm confused.

  15. #45
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,598
    this would be, 3darray[computers][gateway][speed]
    Danger Will Robinson!! Danger!!

    No, no, no. Let's get away from the whole array thingy right now.
    And now for pointers...

    Ah yes well......I don't know where to begin.

    Pointers don't sound too tough, I think I might be onto understanding them, but there's still a few little things that don't make sense...

    by default, when you declare a variable of type int, it just selects a random available range of memory to place its value in, right? So, therefore a pointer would be more static?

    Pointers = Static (doesn't change)
    Variables = Dynamic? (changes)
    Yikes!! Now static and dynamic. Hang on there bud. Forget them terms for right now before we discuss pointers.

    Pointers simply do that - point to something.
    Last edited by VirtualAce; 11-01-2003 at 05:35 PM.

Page 3 of 8 FirstFirst 12345678 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 08:39 AM
  2. Structures, passing array of structures to function
    By saahmed in forum C Programming
    Replies: 10
    Last Post: 04-06-2006, 12:06 AM
  3. Input output with structures
    By barim in forum C Programming
    Replies: 10
    Last Post: 04-27-2004, 09:00 PM
  4. pointers to arrays of structures
    By terryrmcgowan in forum C Programming
    Replies: 1
    Last Post: 06-25-2003, 10:04 AM
  5. Methods for Sorting Structures by Element...
    By Sebastiani in forum C Programming
    Replies: 9
    Last Post: 09-14-2001, 01:59 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21