Initialize const member variables in constructors

This is a discussion on Initialize const member variables in constructors within the C++ Programming forums, part of the General Programming Boards category; Is it possible to initialize private const member variables in a constructor?...

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    2

    Initialize const member variables in constructors

    Is it possible to initialize private const member variables in a constructor?

  2. #2
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    Couldn't you just initialize it in the classes private field

    Code:
    class name
    {
       private:
        const typename name = _value_;
    };

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,119
    Yes.
    Code:
    class Foo {
    public:
    	Foo() : n_(0) {}
    private:
    	const int n_;
    };
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    I remember I did that once and for a minute it was telling me "ISO C++ didn't allow initialization of Constant members" and I restarted and it compiled fine. it was in DevC++ beta 5.

  5. #5
    Mad OnionKnight's Avatar
    Join Date
    Jan 2005
    Location
    Umeň, Sweden
    Posts
    555
    Initialization of constant members is only allowed in an initialization list, if it's done in the body of the constructor you'll get an error.

  6. #6
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    I meant I initialized it in the private sector of the class.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM
  2. Replies: 28
    Last Post: 07-17-2006, 12:35 AM
  3. Another overloading "<<" problem
    By alphaoide in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2003, 11:32 AM
  4. public function returning const char * of private member
    By VanJay011379 in forum C++ Programming
    Replies: 2
    Last Post: 07-26-2002, 04:28 PM
  5. oh me oh my hash maps up the wazoo
    By DarkDays in forum C++ Programming
    Replies: 5
    Last Post: 11-30-2001, 12:54 PM

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