Thread: const method

  1. #1
    Code Warrior
    Join Date
    Nov 2001

    const method


    When do I need to declare const method? And when to use const references?

    Some pseudo-code examples will be just fine.

    Last edited by GaPe; 12-07-2005 at 03:41 AM. Reason: typing errors
    Current projects:
    1) User Interface Development Kit (C++)
    2) HTML SDK (C++)
    3) Classes (C++)
    4) INI Editor (Delphi)

  2. #2
    Join Date
    Aug 2002
    Tucson, Arizona
    1. When you want to tell the compiler your member function doesn't modify data.
    2. When you don't want things messing with you data but want them to use it.

  3. #3
    Registered User
    Join Date
    Apr 2003
    When do I need to declare const method?
    1. As a matter of course for all class functions that don't change the calling object. That way const objects as well as regular objects can call the function.

    2. Passing by reference is more efficient since it avoids copying the argument for the function. However passing by reference means the class function can change the object you are sending to the function. If your function does not need to change the object you are sending it, then declare the function parameter const. That way if the code in the function mistakenly changes the object, the compiler will give you an error. That allows you to use the compiler to catch any programming mistakes you make--instead of having unintended things occur at runtime.
    Last edited by 7stud; 12-07-2005 at 08:14 AM.

  4. #4
    Registered User
    Join Date
    Jan 2005
    If you are unsure whether a methods should be const or not, make it const. Your compiler will complain if it shouldn't be const because it modifies an internal variable.

    Simple, built-in types do not need to be passed by const-reference, but class types should always be passed by const reference unless you have reason to do otherwise. Reasons to do otherwise would include wanting to modify the passed in object (so you would pass by non-const reference) or specifically wanting a copy made (a common operator= technique uses this) or allowing a null argument to be passed in (where you would use a pointer).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Function template has already been defined
    By Elysia in forum C++ Programming
    Replies: 19
    Last Post: 04-14-2009, 10:17 AM
  2. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  3. Classes & Collections
    By Max_Payne in forum C++ Programming
    Replies: 7
    Last Post: 12-11-2007, 01:06 PM
  4. matrix class
    By shuo in forum C++ Programming
    Replies: 2
    Last Post: 07-13-2007, 01:03 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