Thread: Initializing multidimensional array in a class

  1. #1
    Samuel shiju's Avatar
    Join Date
    Dec 2003
    Posts
    41

    Thumbs up Initializing multidimensional array in a class

    Hi,
    How can I initialize a multidimensional array in C++. Below doesn't work. Is there any way other than looping?
    Code:
    //Header file
    class Arena { 
            private: 
                    int map[2][2]; 
    }; 
    
    //CPP file
    Arena::Arena() { 
            map= {
                         {1,2},
                         {3,4}
                      }; 
    }
    I am using MS 2005 C++ express edition.
    Be conservative in what you do, be liberal in what you accept from others.
    RFC 793, "Transmission Control Protocol."


  2. #2
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    QUOTE=shiju]Hi,
    How can I initialize a multidimensional array in C++. Below doesn't work. Is there any way other than looping?
    Code:
    //Header file
    class Arena { 
            private: 
                    int map[2][2]; 
    }; 
    
    //CPP file
    Arena::Arena() { 
            map= {
                         {1,2},
                         {3,4}
                      }; 
    }
    I am using MS 2005 C++ express edition.[/QUOTE]You can initialise 2 dimensional arrays just fine in C++. However you are not doing initialisation, you are dong assignment; You can't do that, and there is no simple or efficient alternative.

  3. #3
    Samuel shiju's Avatar
    Join Date
    Dec 2003
    Posts
    41
    Thanks for the reply.

    You can initialise 2 dimensional arrays just fine in C++. However you are not doing initialisation, you are dong assignment; You can't do that, and there is no simple or efficient alternative.
    How can I do the initialisation?
    Be conservative in what you do, be liberal in what you accept from others.
    RFC 793, "Transmission Control Protocol."


  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    You would normally initialize a class member in the initialization list. However, you cannot initialize an array in this way. You have to assign new values to each entry in the array. Just give a new value for each one, e.g. map[0][0] = 1;.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. question about multidimensional arrays
    By richdb in forum C Programming
    Replies: 22
    Last Post: 02-26-2006, 09:51 AM
  2. array of class object
    By TomButcher in forum C++ Programming
    Replies: 5
    Last Post: 09-03-2005, 09:48 AM
  3. syntax for initializing an array in a class
    By timberwolf5480 in forum C++ Programming
    Replies: 4
    Last Post: 10-14-2003, 08:03 AM
  4. gcc problem
    By bjdea1 in forum Linux Programming
    Replies: 13
    Last Post: 04-29-2002, 06:51 PM