Thread: Initialize const member variables in constructors

  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
    28,412
    Yes.
    Code:
    class Foo {
    public:
    	Foo() : n_(0) {}
    private:
    	const int n_;
    };
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    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
    Registered User OnionKnight's Avatar
    Join Date
    Jan 2005
    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-16-2006, 11:35 PM
  3. Another overloading "<<" problem
    By alphaoide in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2003, 10:32 AM
  4. 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