Thread: const correctness and static member variables

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    271

    const correctness and static member variables

    Are static member variables exempt from "const" declarations? Because this compiled with gcc 4.0.3:
    Code:
    //in the header
    class A
    {
       static int i;
       void inc() const  {i++;}
    }
    
    //and in the source
    int A::i = 0;
    So is it possible to change class member variables even within a constant function as long as they're declared static?

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    static variables are not members of the instance. The instance is constant in inc (the this pointer that is passed implicitly) but static members are not accessed through the instance (or the this pointer).

    In addition, you can also modify non-static member variables in const member functions if you declare them mutable (but that should be very rarely needed).
    Last edited by anon; 02-21-2008 at 05:27 PM.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #3
    Registered User
    Join Date
    Oct 2005
    Posts
    271
    That explains it. Thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  2. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 01:22 PM
  3. const qualifier used on a function argument
    By hzmonte in forum C Programming
    Replies: 27
    Last Post: 04-18-2006, 11:08 PM