const integer array initialization

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

LVL 4
havman56Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

SteHCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
rstaveleyCommented:
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
rstaveleyCommented:
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
Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

itsmeandnobodyelseCommented:
>>>> ...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
SteHCommented:
Hi Alex,

does you code copy the address of the array or its content into the class object?
0
rstaveleyCommented:
Alas it copies the address, which makes it a bad'un for automatic arrays.
0
itsmeandnobodyelseCommented:
>> 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
rstaveleyCommented:
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
itsmeandnobodyelseCommented:
>> which makes it a bad'un for automatic arrays

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

Regards, Alex
0
AxterCommented:
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
AxterCommented:
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
AxterCommented:
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
rstaveleyCommented:
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
havman56Author Commented:
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
rstaveleyCommented:
I think itsmeandnobodyelse and Axter have covered all the possibilities.
0
AxterCommented:
>>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
SirHandoCommented:
Simple Solution....

class Foo
{

}
0
SirHandoCommented:
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
itsmeandnobodyelseCommented:
>> 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
SirHandoCommented:
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
havman56Author Commented:
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
AxterCommented:
>>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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Editors IDEs

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.