Introducing a variable length

First I had

1
2
3
4
5
6
7
8
9
10
//Stack.h
...
const int LEN = 80 ;
class Stack {
public: 
  ...
private:
  ...
  double s[LEN] ;
  ...;


Which worked, but when I tried to change it to have a variable length by

1
2
3
4
5
6
7
8
9
10
//Stack.h
...
int LEN = 80 ;  // "int LEN;" also not working
class Stack {
public: 
  ...
private:
  ...
  double* s = new double[LEN] ;
  ...;


I got
Stack.cc:46: error: âsâ was not declared in this scope
as an error in my other .cc-file

Why isn't this working?
Last edited on
I'm going to take a guess here and say that it has nothing to do with fixed/variable length, but that you're trying to use the variable in a place that doesn't have access to it. You'll have to show us line 46 of Stack.cc for us to have any insights.
To clarify, you're trying to implement a stack class that you can pass in the length to, correct?
You can't call functions (such as new) in your class {..} member variables. Your class {...}does not get executed automatically. It sits somewhere looking pretty so the compiler knows what an object of that class looks like.

If you want the class variable s to be a pointer to a variable length array, you'll have to have that array created using new in a function that gets run. I suggest the constructor.
Last edited on
I'm going to take a guess here and say that it has nothing to do with fixed/variable length, but that you're trying to use the variable in a place that doesn't have access to it. You'll have to show us line 46 of Stack.cc for us to have any insights.

Hope this helps
1
2
3
4
5
6
void Stack::inspect() {
	if(empty()) {cout << "The stack is empty" << endl;}
	for(int i=0 ; i<count-1; i++){
		std:cout << "The value of position " << count-1-i << " is " << s[count-1-i] << endl;
		}
	}	


To clarify, you're trying to implement a stack class that you can pass in the length to, correct?

I'm working towards creating a stack class that I can pass the length to as a constructor argument
If you want the class variable s to be a pointer to a variable length array, you'll have to have that array created using new in a function that gets run. I suggest the constructor


Yep, something like this:
1
2
3
4
5
CStack::CStack(int size)
{
   m_data = new int[size];
   m_size = size;
}


EDIT: In your example, you probably want m_data to be a new double, if your stack is a stack of doubles, that is.
Last edited on
I think Moschops already gave you the answer. Is the 'new' in your constructor or just in the class definition?

Just like you can't do "int myInt = 5;" in a class definition, you can't call new.
Topic archived. No new replies allowed.