CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Dec 2001
    Location
    India
    Posts
    13

    How to declare and use const member variable in class

    Hi NG,
    I want to use a const member variable in a class like
    class abc{
    private :
    const int x;

    };

    How can i Initialise this into some value.
    I am using MS vc++ 6.0.
    Regards\Raghuram.k

  2. #2
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470
    You have to set it in a constructor initialiser list:
    Code:
    class abc
    {
    public:
        abc() : x(0) {}
        abc(const abc& other) : x(other.x) {}
    
    private:
        const int x;
    };
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured