1

I wrote these following codes in Stack.h:

class Stack{
public:
    inline bool full();
    int size();
    inline bool empty();
    bool push(const string&);
    bool pop(string &s);
    bool peek(string &s);
    virtual void print();
    virtual ~Stack(){}

protected:
    vector<string> _elem;
    int const _maxsize=10;    // line X
};

I got the error:

Stack.h:14: error: ISO C++ forbids initialization of member ‘_maxsize’
Stack.h:14: error: making ‘_maxsize’ static
make: *** [Stack.o] Error 1

if I add a static keyword at line X, and initialize the variable outside the class definition, it could be OK.

But my question is that is there any possible way to declare a non-static const variable and still successfully initialize it???

0

3 Answers 3

2

Yes, initialize this in your constructor

const int NumItems;

Foo::Foo():
NumItems(15)
{
//....
}
1

This is valid in C++11. In C++03 you'll have to initialize it in the constructor. Alternitively, in C++11:

class Stack{
    int const _maxsize{10};
};
3
  • OK...I see if I write "Stack():_maxsize(10){}", it will compile.... but why it won't compile if I write Stack(){const int _maxsize=10;}? Commented Nov 19, 2012 at 18:53
  • Because that creates a new variable called _maxsize. Commented Nov 19, 2012 at 18:53
  • Yeah, seems reasonable... "const variable should be initialized as soon as declared". Thanks a lot.. Commented Nov 19, 2012 at 18:57
1

You can use enum

class C {
  protected:
    enum { var = 10 }; 
}

In this case C::var will be compile-time constant, that can be even used in a template.

Also, c++11 allows the declaration you're trying to use.

2
  • Well, I am coding in Mac OS X. So I guess the default compiler is still c++ 03? Commented Nov 19, 2012 at 18:59
  • @Yitong Zhou I'm not well aware of Mac OS X. If you're using gcc, you can try appending -std=c++11 or -std=c++0x (for older versions) to gcc compilation parameters.
    – gluk47
    Commented Nov 19, 2012 at 19:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.