[gnu.g++] Class initialization

tiemann@SUN.COM (Michael Tiemann) (09/19/89)

I guess this reply implies that GNU C++ is not a present compiler....
Try this, but don't try it at home :-)
This will compile and run under GNU C++ 1.36.0.  JTYMLTK.

#include <stdio.h>

typedef char* cstring;

// re first question:

// Unfortunately, your reasonable request still does not seem to be supported
// by C++ compilers.  You should be able to meet your needs by declaring
// a constant static class member, and defining an initial value for it.  
// But present compilers will not allow you to give it an initial value until
// after the class declaration, and will not accept a class declaration with
// an array size whose bounds are not known at class declaration time.

// What today's C++ compilers should be willing to accept, but won't:
//**** This is ugly.  I'm glad GNU C++ does not accept this!!
//
// class cstringstack;
//
// static const int cstringstack::maxStackSize = 100; ?!?!?!?
//
// class cstringstack
// {
//   static const int maxStackSize; ?!?!?!?
//   cstring element[maxStackSize];
//   int top;
// public:
//   cstringstack(): top(0) {}
//   void push(const cstring s){element[top++] = s;}
//   cstring pop(){return element[--top];}
//   cstringstack& popprint(){printf("%s\n",this->pop()); return *this;}
// };

// Or maybe they should accept:
//**** This is even worse!  I'm glad GNU C++ does not accept this either!!
//
// class cstringstack
// {
//   static const int maxStackSize;
//   cstring element[maxStackSize]; ?!?!?!?
//   int top;
// public:
//   cstringstack(): top(0) {}
//   void push(const cstring s){element[top++] = s;}
//   cstring pop(){return element[--top];}
//   cstringstack& popprint(){printf("%s\n",this->pop()); return *this;}
// };
//
// static const int cstringstack::maxStackSize = 100; ?!?!?!?

// the best you can do with today's compilers:
//**** This works with GNU C++, but is boring
// static const int cstringstack__maxStackSize = 100;

// class cstringstack
// {
//   cstring element[cstringstack__maxStackSize];
//   int top;
// public:
//   cstringstack(): top(0) {}
//   void push(const cstring s){element[top++] = s;}
//   cstring pop(){return element[--top];}
//   cstringstack& popprint(){printf("%s\n",this->pop()); return *this;}
// };

//*** How about this:
class cstringstack
{
  const int maxStackSize = 100;
  cstring element[maxStackSize];
  int top;
public:
  cstringstack(): top(0) {}
  void push(const cstring s){element[top++] = s;}
  cstring pop(){return element[--top];}
  cstringstack& popprint(){printf("%s\n",this->pop()); return *this;}
};

void main()
{
  cstringstack stk;

  stk.push("hi mom");
  stk.push("hello dad");
  stk.push("bye world");

  stk.popprint().popprint().popprint();
}