2

I have:

class first{
   private:
   int *array;

   public:
   first(int x){
     array = new int[x][10];
   }

I want to call this class by:

first class1 = new first(10);

Why it doesn't work ? How to inintialize array by size from constructor ??

Samuel Harmer
  • 4,264
  • 5
  • 33
  • 67
  • 2
    In what way does it not work? Does it crash? Where? Does it not compile? What is the error you get? What happened vs. what did you expect? Details please. – i_am_jorf Jan 06 '12 at 19:13
  • error: cannot convert 'int (*)[10]' to 'int*' in assignment. How to inintialize 2dimension array by size from constructor ?? I don't want to use vectors. – makeNicePlusOne Jan 06 '12 at 20:41

2 Answers2

4

Just this is enough:

first class1(10);

new is for when you're allocating a pointer.

first *class1 = new first(10);

Furthermore, you have an incompatibility here:

array = new int[x][10];

array is an int*, but new int[x][10] is a 2D array. I'm not sure which one you want.

For the 1D array:

int *array;
array = new int[x];

For the 2D array:

int (*array)[10];
array = new int[x][10];

That said, you might be better off using std::vector.


Side Note: Since you have memory allocation in the constructor, you should also implement a destructor, copy-constructor, and copy-assignment operator.

Community
  • 1
  • 1
Mysticial
  • 464,885
  • 45
  • 335
  • 332
  • 1
    ...and a copy-assignment operator (per the [Rule of Three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three)). But unless you particularly want to make things hard for yourself, use `std::vector`. – Mike Seymour Jan 06 '12 at 19:22
  • I want to initialize 2dimension array by walue from constructor. object shouldn't be an pointer. Vectors are quite another thing. How to do this ? – makeNicePlusOne Jan 06 '12 at 20:14
  • Answer updated. Multi-dimension arrays can get very ugly. So I suggest you use `vector > array;` unless you have a very good reason not to. – Mysticial Jan 06 '12 at 20:54
2

You've indicate that you want a one-dimensional array (int*) but attempted to allocate a two-dimensional array (new [x][10]).

I'll assume you need one dimension.

The C++ way to do this is with vector.

#include <vector>

class first{
   private:
   std::vector<int> array;

   public:
   explicit first(int x) : array(x) {
   }
};
Mark B
  • 95,107
  • 10
  • 109
  • 188