Thread: If you modify content that a member variable points to, is that const?

  1. #1
    Registered User
    Join Date
    Apr 2007

    If you modify content that a member variable points to, is that const?

    I found an interesting fact that, in a class's const function, you can modify a member varialbe's deference, or the function's parameters, for example:

    class A{
      int* ptr;
      void foo(int x) const{
    Isn't that misleading in C++'s const method's regulation.

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    If you want the pointed-to stuff to be const, do so.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Jun 2007
    yep nothing strange about that.

    The const means you can't modify any of the classes member variables so modifying the parameter passed in isn't surprisingly. While:
    void foo(const int x) constis what prevents the modification of a parameter

    Since the dereference is just memory somewhere you aren't modifying the ptr ptr , but rather what the pointer is pointing to which sounds normal. So operations like
    int *b; ptr = b;
    are prevented by the const as you are actually modifying the member variable.

    What is a bit interesting is that you can indirectly modify a member variable in a const function.

    class A{
      int* ptr;
      int g;
      A(){g = 5; ptr = &g}
      void foo(int x) const{
       ++*ptr; <--- Modifies the member variable g despite being a const.
    Last edited by HyperShadow; 03-07-2008 at 09:42 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. The so annoying LNK2005... please help!
    By Mikey_S in forum C++ Programming
    Replies: 14
    Last Post: 02-01-2009, 04:22 AM
  2. Polynomials and ADT's
    By Emeighty in forum C++ Programming
    Replies: 20
    Last Post: 08-19-2008, 08:32 AM
  3. CProg Fantasy Football version pi
    By Govtcheez in forum A Brief History of
    Replies: 155
    Last Post: 12-26-2006, 04:30 PM
  4. Another overloading "<<" problem
    By alphaoide in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2003, 10:32 AM
  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