Const class members

This is a discussion on Const class members within the C++ Programming forums, part of the General Programming Boards category; How to fix this: Code: class ABC { private: const int a = 5; };...

  1. #1
    Registered User
    Join Date
    Jul 2010
    Posts
    27

    Const class members

    How to fix this:

    Code:
    class ABC
    {
        private:
            const int a = 5;
    };

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,344
    Use an initialisation in the constructors.
    Code:
    class ABC
    {
      public:
        ABC() : a(5) {}
        void func() { cout << a << endl; }
        private:
            const int a;
    };
    
    int main ( ) {
      ABC foo;
      foo.func();
      return 0;
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    2,564
    If you mean how to initialize const data members, the easiest way would be to create the constructor and use the initialization list. See this link.

    Jim

  4. #4
    Registered User
    Join Date
    Jul 2010
    Posts
    27
    Solved, tanks for replying.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 08-12-2009, 04:46 AM
  2. Problems with static const class members
    By sigfriedmcwild in forum C++ Programming
    Replies: 5
    Last Post: 12-05-2004, 06:57 AM
  3. Insight Into const_cast on const data-members
    By shiv_tech_quest in forum C++ Programming
    Replies: 11
    Last Post: 01-21-2003, 04:53 AM
  4. Replies: 1
    Last Post: 12-11-2002, 09:31 PM
  5. Mutable members in const member functions still const
    By ripper079 in forum C++ Programming
    Replies: 3
    Last Post: 10-23-2002, 08:56 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21