5

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.

4
  • 2
    Unless you're completely masochistic: static const unsigned max_size = 4; std::vector<double> array; Stack::Stack() : array(MAX_SIZE){} Commented Jun 4, 2012 at 0:21
  • 1
    Is there a simpler way perhaps? i.e. without using vectors. How can I get the program to accept my array data member with its size being MAX_SIZE? Commented Jun 4, 2012 at 0:30
  • I would get used to using std::vector. I rarely use arrays; I'll use a std::vector be preference nearly every time. The code @Jesse Good has given should work as well. Commented Jun 4, 2012 at 0:44
  • 1
    There are valid reasons to avoid vector. Vector always initializes on a heap while an array can be initialized over stack. Commented Apr 7, 2014 at 10:54

1 Answer 1

5
 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.

Sign up to request clarification or add additional context in comments.

9 Comments

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?
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/…
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.
@Sean: You don't need a separate definition for a static const <integer type> variable like you do in other cases.
@mezhaka: Yes, this form is called value initialization.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.