const char [] troubles with class def's

Started by
11 comments, last by sp00nfed 22 years, 5 months ago
I''m having trouble trying to get my class definitions to work with a const char szAppName[] = "MyApplication". for example: class CApplication { private: // variables HINSTANCE hThisInstance; HWND hWndMain; bool bQuit; const char szAppName[] = "My Application"; }; this causes several weird errors. Any ideas?
Advertisement
AFAIK, if declaring a class variable constant you MUST define it it outside of the class declaration.
You need to initialise it in the constructor or something. You can''t initialise in the class declaration.
You can declare constant members within the declaration but they must be initialize in list form in the constructor.

eg

class MyClass
{
public:
MyClass(void);
~MyClass(void);

private:
const int m_MyInt;
};

MyClass::MyClass(void)
:m_MyInt(3)
{
}

Thanks Gillies, that worked almost perfectly

How would I declare more than one though?

MyClass::MyClass(void)
:m_MyInt(3), m_MyInt2(4)
{
}







Got it
If you want to define a constant of integral type (that is, int, double, etc.) inside a class, you can declare it static and initialize directly.

    #include <cstdio> class CCLass{public:  static const int ID = 234;}; int main(){  printf("%i", CCLass::ID);}    


However this will not work with char[].

Edited by - Advanced Bug on October 22, 2001 5:24:16 AM
That doesn''t work for ints, either, at least in my compiler:
  class Test{    static const int m_const = 42;};  

C:\projects\test\test.h(6) : error C2258: illegal pure syntax, must be ''= 0''
C:\projects\test\test.h(6) : error C2252: ''m_const'' : pure specifier can only be specified for functions

My understanding is that C++ doesn''t allow member initialization in the class definition, period. What version are you using that allows this?
AFAIK, static members must be intialized at file scope, which means Advanced Bug''s example can''t be right.
Just wondering, if you have a constant inside a class wouldnt it make it so a new constant is allocated for each

instance of the class? I mean, it would allocate new memory for each constant, and it will be the same constant, so

if you have 1000 objects you will be wasting a lot of memory in duplicate values wouldnt you? why not declare it

outside the class, and have all instances access the same memory? I am not sure if the compiler would know of

something like this to optimise, so I ask.

This topic is closed to new replies.

Advertisement