Reputation: 33
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 ??
Upvotes: 2
Views: 675
Reputation: 471569
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.
Upvotes: 4
Reputation: 96301
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) {
}
};
Upvotes: 2