Thread: how do i define a const inside a class under private

  1. #1
    Unregistered
    Guest

    how do i define a const inside a class under private

    how do i define a const inside a class under private

    when i try to define say

    class abc
    {

    private: //or public whatever
    cont int a = 12; //i get 'illegal' errors

    }

    using vc6 9x

  2. #2
    Banned Troll_King's Avatar
    Join Date
    Oct 2001
    Posts
    1,784
    class abc
    {
    abc() {a = 12}
    private: //or public whatever
    const int a;

    }

    I think you can do this when it is initialized in the constructor.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    7
    As the Troll mentioned, you can set constant members in the constructor like so:

    class MyClass
    {
    public:
    MyClass() : cvar(5)
    {
    }

    private:
    const int cvar;
    };

    If you're going to use a constant data member, however, you should declare it as static. That way all instances of an object only share that one constant rather than every instance having their own version and all of them being the same.

    class MyClass
    {
    private:
    static const int cvar;
    };

    Remember to define the static somewhere in your sources or you will get a linker error:

    const int MyClass::cvar = 5;

    Hope this helps

  4. #4
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    ..or you could use an enum to guarantee that it will be evaluated at compile time and not have storage allocated (as MSVC 6.0 doesn't support initialisation of static consts from within class declarations) -

    Code:
    class abc
    {
    	enum {a =12};
    };
    zen

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Changing flags from a DLL?
    By RobotGymnast in forum C++ Programming
    Replies: 17
    Last Post: 10-27-2008, 01:34 PM
  2. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  3. Replies: 3
    Last Post: 05-13-2007, 08:55 AM
  4. build errors migrated from dx9b to dx9c sdk
    By reanimated in forum Game Programming
    Replies: 4
    Last Post: 12-17-2004, 07:35 AM