Thread: Const class members

  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 int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    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.

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    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, 07: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, 05:53 AM
  4. Replies: 1
    Last Post: 12-11-2002, 10: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