const on functions

This is a discussion on const on functions within the C++ Programming forums, part of the General Programming Boards category; Hi! I know the meaning of the const in the parameter field but I don't know exactly what it means ...

  1. #1
    Code Warrior
    Join Date
    Nov 2001
    Posts
    669

    Question const on functions

    Hi!

    I know the meaning of the const in the parameter field but I don't know exactly what it means if you declared it after the parameter field.

    Code:
    bool find(const String &str) const; // what does this const do?
    bool find(const String &str);
    Current projects:
    1) User Interface Development Kit (C++)
    2) HTML SDK (C++)
    3) Classes (C++)
    4) INI Editor (Delphi)

  2. #2
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    const after a function name is only relevant for a method of a class. With regular functions, you can make all the parameters const to prevent the function from changing them. However, with a method of a class, there is another entity involved--the object that called the method. What if you want to ensure that the method does not change the object? To do that, you put const after the method to enforce your desire that the method not change the object.

    Only constant methods can be called by objects that were declared as constant. A constant object has to be absolutely sure a rogue method won't harm it before entering its lair. On the other hand, objects that aren't declared as constant can happily call a constant method--they don't care whether they are changed or not, so they could care less that a function guarantees they won't be changed.
    Last edited by 7stud; 05-10-2005 at 09:19 AM.

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, 03:13 PM
  2. Replies: 7
    Last Post: 06-16-2006, 09:23 PM
  3. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
  4. Class functions can't use const =/
    By neandrake in forum C++ Programming
    Replies: 10
    Last Post: 12-02-2004, 12:48 AM
  5. Problem with Template Function and overloaded equality operator
    By silk.odyssey in forum C++ Programming
    Replies: 7
    Last Post: 06-08-2004, 04:30 AM

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