I'm trying to initialize an array in my constructor's intialization list, and I want the array to have the size MAX_SIZE, which is a public static const in my Stack class. How can I get it to work? The compiler complains, saying they have incompatible types in assignment of 'double' to 'double[0u]'
Here is my code:
class Stack {
public:
Stack();
static const unsigned MAX_SIZE;
private:
double array[];
unsigned elements;
}; // class Stack
Stack::Stack(): array( array[MAX_SIZE] ), elements(0) {}
const unsigned Stack::MAX_SIZE = 4;
Thanks in advance for your help.
1 Answer 1
class Stack {
public:
Stack();
static const unsigned MAX_SIZE = 4;
private:
double array[MAX_SIZE];
unsigned elements;
}; // class Stack
Stack::Stack(): array(), elements(0) {}
But, std::vector would be better as mentioned in the comments.
answered Jun 4, 2012 at 0:32
Jesse Good
52.8k15 gold badges133 silver badges174 bronze badges
Sign up to request clarification or add additional context in comments.
9 Comments
Sean
I see.. so, basically, avoid initializing the array in the initialization list. Not possible, correct? Also, is it not possible to write my MAX_SIZE constant after main the way I did?
Sean
Reason I ask is cause I read differently on here, that the definition should be outside of the class: publib.boulder.ibm.com/infocenter/comphelp/v8v101/…
Jesse Good
array() in the intializer list zero initializes all the elements. You are correct, and I didn't define MAX_SIZE because I am only using it's value in the code. Define MAX_SIZE outside the class if you need to use it elsewhere.Jerry Coffin
@Sean: You don't need a separate definition for a
static const <integer type> variable like you do in other cases.Jesse Good
@mezhaka: Yes, this form is called
value initialization. |
Explore related questions
See similar questions with these tags.
lang-cpp
static const unsigned max_size = 4; std::vector<double> array; Stack::Stack() : array(MAX_SIZE){}std::vector. I rarely use arrays; I'll use astd::vectorbe preference nearly every time. The code @Jesse Good has given should work as well.