Whats the point of const?

This is a discussion on Whats the point of const? within the C++ Programming forums, part of the General Programming Boards category; I've noticed that you can put constants within a class, and then change them as if they were normal values ...

  1. #1
    Registered User
    Join Date
    Sep 2003
    Posts
    28

    Unhappy Whats the point of const?

    I've noticed that you can put constants within a class, and then change them as if they were normal values by const flagged member functions. I want to know, what do you expert programmers out there actually use constants for? Whats the advantage. I would really just like to hear a scenario where a constant would be better, because I can't think of one. Sorry, it's just driving me nuts

  2. #2
    lyx
    lyx is offline
    Amateur
    Join Date
    Sep 2003
    Posts
    228
    and then change them as if they were normal values by const flagged member functions
    Are you sure of that?

    Well, for constants stuffs, I cannot answer because:
    1. I'm no expert.
    2. I don't use them often, just in my interfaces.
    3. Too much const keywords make my code ugly.

  3. #3
    Registered User
    Join Date
    Jul 2003
    Posts
    450
    const insures values are not changed w/o reason
    for instance
    const data members are not meant to be changed and const functions insure values are not changed within the function

    like accessor methods
    void get_member() const;
    insures the get_member doesn't accidently alter members of the class which it is not intended to do anyway

  4. #4
    lyx
    lyx is offline
    Amateur
    Join Date
    Sep 2003
    Posts
    228
    I don't think one is silly enough to change what he wants to be constant.
    Actually, in my opinion, const modifiers are there to give a hint to those who use your library or read your code, nothing more because, except if your object model is really bad, you shouldn't be experiencing troubles.

  5. #5
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    i'm no expert, but...

    it's called readability - not only does it stop you from doing it by accident, people that read your program know what your intention was...
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  6. #6
    Cat
    Cat is offline
    Registered User
    Join Date
    May 2003
    Posts
    1,571
    Also, const is really helpful in limiting interfaces. Example: You have a file class, and one of the parameters lets the user get the filename.

    If you make the return type "char *", then the user of your class can modify the filename -- this might cause disasterous results, if the filename is allowed to change without you knowing about it. Returning a non-const pointer to a data member is almost always A Bad Idea.

    If the return type was const char *, the user would NOT be able to modify this without subverting the type system -- and if they willfully break the type system, they are responsible.

    Now, you make accessor functions const as well, because maybe someone else wants to use a pointer to a const object, and they probably want to be able to use it for something.

    const-correctness is NOT just an afterthought, it's a core idea for building safe code, especially but not limited to cases where multiple people are using the same interface. In general, if a function does not modify a parameter, make it const. If a function does not change the internal state of an object, make it const. If a return value should not be modified, make it const.

    Note with anything that is passed by copy or returned by copy, const has no effect.
    Last edited by Cat; 09-29-2003 at 09:01 PM.
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

  7. #7
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,088

    Re: Whats the point of const?

    Originally posted by Grins2Pain
    I've noticed that you can put constants within a class, and then change them as if they were normal values by const flagged member functions.
    Uhh, either I'm misunderstanding you, or I think you are wrong. I don't see how constants within a class can be modified by const flagged member functions. Maybe you can give a small example.

    Here's my example of when const is better:
    Code:
    // SocketServer.h
    ...
    class SocketServer
    {
    public:
        SocketServer(int listenPort);
        ...
        int GetListenPort() const { return LISTEN_PORT; }
        ...
    private:
        const int LISTEN_PORT;
        ...
    };
    ...
    
    // SocketServer.cpp
    ...
    SocketServer::SocketServer(int listenPort) : LISTEN_PORT(listenPort)
    {
    ...
    }
    ...
    I made LISTEN_PORT const because in my scenario above it should never change for any instance of the socket server. Since it is const, I will never accidentally set it to something else in the code. I would have to specifically remove the const specification to do so, as would any other person working on this code.

    I made GetListenPort() const because it does not affect the state of the object and so if somebody has a const SocketServer object they will be able to call that method. Why would somebody ever have a const SocketServer object? Maybe they have a const reference to it so they can log info like the Port number. Maybe they did that for efficiency reasons, since I believe compilers can optimize in certain situations when they know an object won't be modified.

    Anyway, that is my example.

  8. #8
    lyx
    lyx is offline
    Amateur
    Join Date
    Sep 2003
    Posts
    228
    Originally posted by major_small
    it's called readability - not only does it stop you from doing it by accident, people that read your program know what your intention was...
    Originally posted by lyx
    to give a hint to those who use your library or read your code
    And I do know about the const rules, but it doesn't mean that you have to use const every now and then.

  9. #9
    That Creepy Network Guy DeepBlackMagic's Avatar
    Join Date
    Feb 2003
    Posts
    265
    Just out of curiousity, how would one go about breaking the type rules? To play with this, I created a const int x. x=6. bla bla bla. Now, how do you change his value? I tried an int pointer to x, and then to change the value of his address in memory, which suprisingly didnt work. When i printed the contents of x, it was still 6 eventhough the contents of what the pointer pointed to were different. To my knowledge const variables arent stored any different in memory, so why did my attempt fail? And what is the correct way to subvert a const variable?

  10. #10
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,088
    The "correct" way? A way that will work is using a cast, preferably const_cast<>.

  11. #11
    Registered User
    Join Date
    May 2003
    Posts
    161
    Here is a similar program to the one you're talking about:
    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
      const int x = 6;
      int* p = const_cast<int*>(&x);
    
      *p = 20;
    
      cout << x << " " << *p << endl;
      return 0;
    }
    
    /**
     * output:
     * 6 20
     */
    What's happening here, is that you're telling your compiler that x is const. Therefore, it makes the reasonable assumption that the value won't change and it effectively does a substitution in the code - it replaces all x's with 6's.

  12. #12
    Cat
    Cat is offline
    Registered User
    Join Date
    May 2003
    Posts
    1,571
    It also may elect to store const variables in locations of memory that your program does not request write access to. In this case, you could never write to it, no matter the trickery involved, because the OS itself doesn't allow writes to that region to succeed.
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

  13. #13
    That Creepy Network Guy DeepBlackMagic's Avatar
    Join Date
    Feb 2003
    Posts
    265
    if const_cast cant do it, are there any other ideas on how it might be accomplished? Assuming we could get write access to memory, how would we go about finding where its hiding the variable? And what is the pointer pointing to? does it just create a copy of the variable in the programs memory space and reference it?
    Last edited by DeepBlackMagic; 09-30-2003 at 03:54 PM.

  14. #14
    Registered User
    Join Date
    May 2003
    Posts
    161
    There is really no way around the situation I described in my last post. The subsitutions (probably swapping an identifier node for an integer literal node in some intermediate tree representation) occur during compile time so you have no access to it during runtime. A variable still exists, but changing it won't modify any references to it becaues the substitutions have already been made.

    If you find a compiler that implements const as Cat described, then you might be able to circumvent that system, but you will almost certainly be hit with some type of access violation.

    If you're still determined to break the type system, you can just wrap a const variable in a class and initialize it with a constructor - then return a non-const pointer to it and you can modify the variable as many times as you want.

    Code:
    #include <iostream>
    using namespace std;
    
    class Test
    {
    public:
      Test(int i): x(i) {}
      int* getPointerToX() { return const_cast<int*>(&x); }
      int getX() { return x; }
    private:
      const int x;
    };
    
    int main()
    {
      Test test(6);
      int* p = test.getPointerToX();
    
      *p = 20;
    
      cout << test.getX() << endl;
    }
    
    /**
     * output:
     * 20
     */
    Last edited by thefroggy; 09-30-2003 at 04:38 PM.

  15. #15
    Registered User
    Join Date
    Jan 2003
    Posts
    311
    The correct way is to not ask for a const if you don't really want one. The problem is not so much that x lives at a read-only address(it probably doesn't), but that the compiler doesn't bother generating the code to go fetch the value from a memory location if it already knows the value. This brings up something that I had been thinking about earlyer, the easest way to do this is to declare your type const volatile. I used to think of these qualifiers as opposites, but this question brings up the subtile distiction that shows how they can live in harmony. const means you cannot change this AND assume this never changes. volatile means assume this can change at any time for unknown reasons. I don't know how standard this behavior of const volatile is, but gcc 3.2 performs the expected "pessimisation" and prints the changed const value.

Page 1 of 2 12 LastLast
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. Classes & Collections
    By Max_Payne in forum C++ Programming
    Replies: 7
    Last Post: 12-11-2007, 01:06 PM
  3. Need help implementing a class
    By jk1998 in forum C++ Programming
    Replies: 8
    Last Post: 04-05-2007, 04:13 PM
  4. Replies: 7
    Last Post: 06-16-2006, 10:23 PM
  5. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 12:58 PM

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