Thread: const on functions

  1. #1
    Code Warrior
    Join Date
    Nov 2001

    Question const on functions


    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.

    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
    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, 04: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, 01: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