Solved

const integer array initialization

Posted on 2004-10-28
876 Views
Last Modified: 2013-12-14
I wnat to initialise the const integer array. CAn any one help  me ?

class Test
{
public:
       Test( int a[2]);
private:
      const int m_array[2];
};


Test::Test( int a[2]): m_array(a)
{

}


main()
{
      int array[2]={1,2};

      Test obj(array);
}

i m getting error in VC
error C2536: 'Test::m_array' : cannot specify explicit initializer for arrays

0
Question by:havman56
    22 Comments
     
    LVL 13

    Accepted Solution

    by:
    When you don't specify an index you are working on the memory address. But this is most likely what you want to do here. I guess you want to copy the values from the parameter array to the internal array. This needs to be done in the constructor since in addition you need to override the constness of the member array. Why is it constant if you change it in the constructor?
    0
     
    LVL 17

    Expert Comment

    by:rstaveley
    Arrays are primitive and therefore do not have constructors.

    Use a const std::vector<int> and you can use the templatised iterator ctor with pointers to begin and end in the array as iterators in your initialiser list.

    i.e.
    --------8<--------
    #include <vector>

    class Test
    {
    public:
          Test(int a[2]);
    private:
          const std::vector<int> m_array;
    };

    Test::Test(const int a[2]) : m_array(&a[0],&a[0]+2)    /* end iterator is &a[0]+2 */
    {
    }

    main()
    {
         int array[2]={1,2};
         Test obj(array);
    }
    --------8<--------
    0
     
    LVL 17

    Assisted Solution

    by:rstaveley
    Oops, slipped a const in the ctor out of [good] habit.

    Change also...

    > Test(int a[2]);

    ...to...

       Test(const int a[2]);

    ...and feel the warm glow of const-correctness ;-)
    0
     
    LVL 39

    Assisted Solution

    by:itsmeandnobodyelse
    >>>> ...and feel the warm glow of const-correctness ;-)

    Or with that (not using std::vector) ... so not feel the cool breeze of C++ standard ;-)

    class Test
    {
    public:
          Test( const int a[2]);
    private:
         const int* m_array;
    };


    Test::Test( const int a[2]): m_array(a)
    {

    }

    main()
    {
         int array[2]={1,2};

         Test obj(array);
    }

    Regards, Alex


    0
     
    LVL 13

    Expert Comment

    by:SteH
    Hi Alex,

    does you code copy the address of the array or its content into the class object?
    0
     
    LVL 17

    Expert Comment

    by:rstaveley
    Alas it copies the address, which makes it a bad'un for automatic arrays.
    0
     
    LVL 39

    Expert Comment

    by:itsmeandnobodyelse
    >> does you code copy the address of the array or its content into the class object?

    It copies the address, so correctly the member should be defined as

           const int*&  m_array;

    to make that clear.

    There is no way to initialize a non-static const array (or pointer) copying values beside of type casting of course (beware..., beware...). With VC Compiler even the member definition

              const int m_array[2];

    would not compile as the constructor could not initialize an array.

    Regards, Alex



    0
     
    LVL 17

    Expert Comment

    by:rstaveley
    It never really occurred to me before, but isn't it odd how string literals are treated differently from arrays of other primitives?

    e.g.

         Test obj({1,2});    // Error

    I wonder if K&R were ever tempted to stick an array in the data segment for this kind of expression?
    0
     
    LVL 39

    Expert Comment

    by:itsmeandnobodyelse
    >> which makes it a bad'un for automatic arrays

    Yes, but const pointers are second choice for dynamic arrays anyhow .. ;-)

    Regards, Alex
    0
     
    LVL 30

    Assisted Solution

    by:Axter
    Here's one method:

    class Test
    {
    public:
          Test(const int a[2]);
            ~Test(){delete[] (int*)m_array;}
    private:
         const int* m_array;
           const int* InitializeArray(const int a[2])
           {
                 int* ptr = new int[2];
                 for(int i = 0;i < 2;++i) ptr[i] = a[i];
                 return ptr;
           }
    };

    Test::Test( const int a[2]): m_array(InitializeArray(a))
    {

    }
    0
     
    LVL 30

    Expert Comment

    by:Axter
    FYI:

    In above code, the destructor is using a cast, which is not needed if you're using a compliant C++ compiler.  If you're using something like VC++ 6.0, you'll need the cast.
    0
     
    LVL 30

    Expert Comment

    by:Axter
    If you're not afraid of using templates, you can also use the following method:
    class Test
    {
    public:
          template<typename T>
                Test(T &a): m_array(InitializeArray(a, a[0])){}
          ~Test(){delete[] (int*)m_array;}
    private:
          const int* m_array;
          template<typename T, typename T0>
          const int* InitializeArray(T &a, T0 &a0)
          {
                const int ArraySize = sizeof(T)/sizeof(T0);
                int* ptr = new T0[ArraySize];
                for(int i = 0;i < ArraySize;++i) ptr[i] = a[i];
                return ptr;
          }
    };


    Using the above method, gives you the advantage of being able to use the class with different size arrays.

    int array1[]={1,2};
    Test test1(array1);

    int array2[]={1,2, 3, 4, 5, 6};
    Test test2(array2);

    int array3[]={1,2, 3, 4};
    Test test3(array3);


    Of course you would then want to have a member variable that would specify the size of the array.
    0
     
    LVL 17

    Expert Comment

    by:rstaveley
    Like the vector solution though, it's annoying that you need to resort to the free store for a constant array, when it ought to be possible to have one in automatic storage.
    0
     
    LVL 4

    Author Comment

    by:havman56
    Thanks for all ur inputs....


    But i cannot change array to vector or so..

    i have to use const int array as data member i need to initialise it in constructor.

    anyotherway to initialise const array in ctor.

    ManyThanks!
    0
     
    LVL 17

    Expert Comment

    by:rstaveley
    I think itsmeandnobodyelse and Axter have covered all the possibilities.
    0
     
    LVL 30

    Expert Comment

    by:Axter
    >>But i cannot change array to vector or so..

    Why?

    Why can't you have a const int* type?

    The method I posted does initialize the const int* type in the constructor initialize list.
    0
     
    LVL 1

    Expert Comment

    by:SirHando
    Simple Solution....

    class Foo
    {

    }
    0
     
    LVL 1

    Assisted Solution

    by:SirHando
    Oppsss.. try again..

    class Foo
    {  
        public:
            Foo( );
       private:
            static const int MY_CONST_ARRAY[];
            static const unsigned  ARRAY_SIZE;
    };

    in .cpp file

    #include "Foo.hpp"

    const Foo::MY_CONST_ARRAY[] =
    {
        { 2, 3, 4, 5, 6, 7, 8, 9 }
    };

    const unsigned Foo::ARRAY_SIZE = sizeof(Foo::MY_CONST_ARRAY)/sizeof(Foo::MY_CONST_ARRAY[0]);

    Foo::Foo( )
    {
    }

    Regards,

    SirHando


       
    0
     
    LVL 39

    Expert Comment

    by:itsmeandnobodyelse
    >> Simple Solution....

    Yes, static arrays might be a solution, if there is only one instance of class Foo or if all instances were using the same const array. Howver, most classes will need more than one instance ... and there is no way to define a non-static const member array in C++ beside of defining it as a pointer. But there is no major difference between a const pointer and a const array as long as you don't break constness.

    Regards, Alex
    0
     
    LVL 1

    Expert Comment

    by:SirHando
    True,

    I didn't read the initial question very well.

    As stated, if you want different objects to have different const arrays, then they only way is via a pointer.

    Regards,

    SirHando
    0
     
    LVL 4

    Author Comment

    by:havman56
    still i did not get answer from anyone.

    u may ask why and so on....


    i need to use const int array then need to initialise it ?

    axter thanks for ur input but i cant change ....the way u say
    0
     
    LVL 30

    Expert Comment

    by:Axter
    >>axter thanks for ur input but i cant change ....the way u say
    Why?

    If you can explain the cause of your restrictions, we could probably give you a good alternative.
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone. Privacy Policy Terms of Use

    Featured Post

    Hire Top Freelancers to Complete C++ Projects

    Source the talented Expert Exchange community
    for top quality work on your C++ projects.

    Hire the best. Collaborate easily. Get quality work.

    Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
    Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
    The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.
    The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.

    875 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now