Define an array of non-fixed size as a function inside a class

The following does not work for sure.
1
2
3
4
5
class A{
public:
int d;
double x[d];
};

So I define class A as follows
1
2
3
4
5
6
class A{
public:
int d;
double* x;
A();
};

and in the .cpp file I did
1
2
3
A::A(){
double* x = new double [d];
}

Is there a better way of doing this?

Things get more complicated if we want to to do the same with a function which returns an array of non-fixed size inside a class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class A{
	public:
	int d;
	double* f (double*);
};

double* A::f (double* fx){
double* s = new double [d];
for (int i=0; i<d; ++i){//assigning some values to fx[i]
	s[i] = fx[i];
	for (int j = 0; j<i; ++j)
	s[i] += fx[j];
}
return s;
}


I got no error in
1
2
3
4
5
6
double* fx;
fx = new double [2];
fx[1]=2;fx[0]=1;
A testA;
testA.d=2;
printf("\n%1.1f,%1.1f\n",testA.f(fx)[0],testA.f(fx)[1]);


1
2
3
4
$ g++ main.cpp free_bndry.cpp

$ ./a.out
1.0,3.0


Does that look fine? Is there a better way of doing this?
Can you use a vector or list or some other STL container that doesn't have a fixed size?

Check out the reference section at the top left of this page to see how to use them.

Btw, when compiling under g++ use the -Wall -Wextra -pedantic options to set the warning level at it's maximum.

Also use -std=c++11 to take advantage of the C++11 standard.

And the -o option to give the executable a name.

HTH
Thanks TheIdeaMan,

I wonder if by using STD I may loose time efficiency.
I think you will find the STL to be very efficient - it wouldn't be there if it wasn't.

Hope all goes well.
Topic archived. No new replies allowed.