0

So I've looked around and nothing I found has helped me so far.

I have the following header file for my class.

#ifndef CONGERA2_H
#define CONGERA2_H

typedef float Element300;

class Stack300
{
public:
    Stack300 ();
    Stack300 (const int);
    Stack300 (Stack300 &old);
    ~Stack300();
    void push300(const Element300);
    Element300 pop300();
    void viewTB300();
    void viewBT300();

private:
    const int MAX_STACK;
    Element300 * stackArray;
    int top;

};

#endif

And I'm trying to initialize MAX_STACK. If I set it equal to something I get a warning, which would normally be fine but I must transfer this code to Linux afterwards and I can't do that because it says that MAX_STACK is undefined in my three constructors. I've also tried defining it in my class functions file in the first constructor but then I get an error saying that MAX_STACK is not defined in the constructor.

Here is the constructors for my class functions if they are needed.

#include <iostream>
#include "congera2.h"
using namespace std;

Stack300::Stack300 (): MAX_STACK(10)
{
    stackArray = new float[3];

    for (int i = 0; i < 3; i++)
    {
    stackArray[i] = '\0';
    }

    top = -1;

return;
}

Stack300::Stack300 (const int size) : MAX_STACK (10)
{
    stackArray = new float[MAX_STACK];

    for (int i = 0; i < MAX_STACK; i++)
    {
    stackArray[i] = '\0';
    }

    top = -1;

return;
}

Stack300::Stack300 (Stack300 &old) : MAX_STACK (10)
{
    top = old.top;
    int i = 0;

    while (top != old.top)
    {
    stackArray[i] = old.stackArray[i];
    i = i + 1;
    top = i;
    }
}
C0UG3R
  • 25
  • 1
  • 9
  • It should work using a constructor initialization list, as you do it now. Or if using C++11, can initialize it directly in the header, at the point of declaration. Can you post the exact error message you're getting? – vsoftco Oct 14 '15 at 00:58
  • 3
    If it's the same value for all constructors, make it `static const int MAX_STACK = 10` in your class declaration – Rostislav Oct 14 '15 at 00:59
  • [works for me](http://coliru.stacked-crooked.com/a/a686e7df2f780419) – Bryan Chen Oct 14 '15 at 00:59
  • I'm using Tera Term to transfer it to Linux and the error in there is "error: uninitialized member Stack300::MAX_STACK with const type const int". On Code::Blocks (where I'm originally compiling the code) I don't have any errors at the moment because I added the : MAX_STACK (10) afterwards but originally I was getting the same error that I am getting on Tera Term now. EDIT: Rostislav's solution fixed it for me, thanks! – C0UG3R Oct 14 '15 at 01:02

1 Answers1

0

Error:

class A
{
public:
    const int x=8; // error (c++98/03)
};

Fix 1

class A
{
public:
    const int x;

    A() : x(8)  // ok
    { }
};

Fix 2

class A
{
public:
    const static int x;
};

const int A::x=8; // ok
ar2015
  • 5,558
  • 8
  • 53
  • 110