CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1
    Join Date
    Aug 2002
    Location
    Armenia
    Posts
    62

    Initialization of an array.

    Hi there..

    struct A{
    A(int){}
    };

    struct B{
    B() : ????
    A a[10];
    };

    How can I initialize array of A in initialization list?

  2. #2
    Join Date
    Nov 2002
    Location
    Sofia, Bulgaria
    Posts
    661
    be more specific... what exactly do you want to do? I'm not sure i understand.
    It's only when you look at an ant through a magnifying glass on a sunny day that you realise how often they burst into flames

  3. #3
    Join Date
    Dec 2001
    Location
    Ontario, Canada
    Posts
    2,236
    he wants to pass data to a constructor, but has an array of 10 objects. I don't know how to do this on the stack.

  4. #4
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Initialization of an array.

    Originally posted by dav79
    Hi there..

    struct A{
    A(int){}
    };

    struct B{
    B() : ????
    A a[10];
    };

    How can I initialize array of A in initialization list?
    You can't. You have to initialize A in the constructor body. But then your code will not compile, due to the fact that your A class has no default constructor, and you are attempting to create an array of A. Without a default constructor, your A array is unusable.

    So you have a choice:

    a) Give your A array a default constructor (a constructor that will take no arguments), and initialize the A array in the body of the B constructor, or

    b) Use vectors. Then you can initialize the vector without adding a default constructor to A. Here is one way to use the vectors to do what you want.
    Code:
    #include <vector>
    
    struct A{
       A(int){}
    };
    
    struct B {
       B() : a(10) { a[0] = 0; a[1] = 12; /*etc*/ }
       // If you want to initialize the A to a single value:
       //  B() : a(10, 0) { } // Initialize all 10 elements to 0
       std::vector<A> a;
    };
    There are probably other methods. Maybe the fixed array class at www.boost.org has a way of doing this. In any event, you can't initialize 'C' arrays in the initialization list.

    Regards,

    Paul McKenzie

  5. #5
    Join Date
    Nov 2002
    Location
    Sofia, Bulgaria
    Posts
    661
    ahaaaaaaa! now I get it! I was soooo confused when I saw this that couldn even think!

    struct B{
    B() : ????
    A a[10]; // its weird
    };
    It's only when you look at an ant through a magnifying glass on a sunny day that you realise how often they burst into flames

  6. #6
    Join Date
    Aug 2002
    Location
    Armenia
    Posts
    62
    Thanks a lot guys..

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured