Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

const integer array initialization

Posted on 2004-10-28
25
Medium Priority
?
895 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
Comment
Question by:havman56
  • 6
  • 5
  • 4
  • +3
25 Comments
 
LVL 13

Accepted Solution

by:
SteH earned 100 total points
ID: 12431249
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
ID: 12431447
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
rstaveley earned 100 total points
ID: 12431455
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 39

Assisted Solution

by:itsmeandnobodyelse
itsmeandnobodyelse earned 100 total points
ID: 12432424
>>>> ...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
ID: 12432428
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
ID: 12432589
Alas it copies the address, which makes it a bad'un for automatic arrays.
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 12432629
>> 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
ID: 12432638
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
ID: 12432667
>> 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
Axter earned 100 total points
ID: 12433557
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
ID: 12433576
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
ID: 12433719
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
ID: 12435424
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
ID: 12441512
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
ID: 12441689
I think itsmeandnobodyelse and Axter have covered all the possibilities.
0
 
LVL 30

Expert Comment

by:Axter
ID: 12442992
>>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
ID: 12510265
Simple Solution....

class Foo
{

}
0
 
LVL 1

Assisted Solution

by:SirHando
SirHando earned 100 total points
ID: 12510278
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
ID: 12512475
>> 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
ID: 12517007
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
ID: 12533196
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
ID: 12533280
>>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

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Programmer's Notepad is, one of the best free text editing tools available, simply because the developers appear to have second-guessed every weird problem or issue a programmer is likely to run into. One of these problems is selecting and deleti…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

916 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