Thread: default values for struct members (noob q)

  1. #1
    Registered User Mr_Jack's Avatar
    Join Date
    Oct 2003
    Posts
    63

    default values for struct members (noob q)

    how do you intialize struct members?

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    A struct can have constructors and functions associated with it just like a class can. Just make a constructor for the struct that assigns default values to the struct's data members. Is this what you mean or are you talking about something else?

    Code:
    #include <iostream>
    
    struct mystruct
    {
        int iVal;
        float fVal;
        mystruct() : iVal(5), fVal(9.9f) {}
    };
    
    int main()
    {
        mystruct item;
    
        std::cout << item.iVal << ' ' << item.fVal << std::endl;
    
        return 0;
    }
    Should output: 5 9.9
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User Mr_Jack's Avatar
    Join Date
    Oct 2003
    Posts
    63
    that is excactly what I wanted to know. Thank you.

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >how do you intialize struct members?
    The alternative is an initialization list upon variable creation:
    Code:
    #include <iostream>
    
    struct mystruct {
      int   iVal;
      float fVal;
    };
    
    int main()
    {
      mystruct item = { 5, 9.9 };
      
      std::cout<< item.iVal <<' '<< item.fVal <<std::endl;
    }
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. disposing error
    By dropper166 in forum C# Programming
    Replies: 2
    Last Post: 03-30-2009, 11:53 PM
  2. Array members copied by the default copy constructors?
    By cyberfish in forum C++ Programming
    Replies: 4
    Last Post: 02-18-2008, 12:46 AM
  3. constructors
    By shrivk in forum C++ Programming
    Replies: 7
    Last Post: 06-24-2005, 09:35 PM
  4. Need help in classes
    By LBY in forum C++ Programming
    Replies: 11
    Last Post: 11-26-2004, 04:50 AM
  5. Serial Communications in C
    By ExDigit in forum Windows Programming
    Replies: 7
    Last Post: 01-09-2002, 10:52 AM