structures

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ankit4284
    New Member
    • Oct 2008
    • 1

    structures

    why cant we initialise a member variable inside a structure or a class?
  • archonmagnus
    New Member
    • Jun 2007
    • 113

    #2
    You can, but it has to be inside of a constructor. Try the following:

    [code=cpp]
    #include <iostream>

    using namespace std;

    struct XYZZY
    {
    double foo, bar;

    // Here's the constructor
    XYZZY()
    {
    foo = 2.718281828;
    bar = 1.618;
    }
    // Here's the destructor
    ~XYZZY(){};
    } xyzzy;

    int main (void)
    {
    cout<<"Foo = "<<xyzzy.foo<<e ndl
    <<"Bar = "<<xyzzy.bar<<e ndl;

    return;
    }
    [/code]

    In this example, you've initialized the values of foo and bar inside the constructor within the struct XYZZY. If I understand your inquiry right, that should help.

    Comment

    • gpraghuram
      Recognized Expert Top Contributor
      • Mar 2007
      • 1275

      #3
      Originally posted by ankit4284
      why cant we initialise a member variable inside a structure or a class?
      You have to use the constructor to do this and i think thats the only way to initialize the member.

      Raghu

      Comment

      Working...