const on a function???

This is a discussion on const on a function??? within the C++ Programming forums, part of the General Programming Boards category; I was looking at some C++ code and I notice that a function had const at the end of it. ...

  1. #1
    Registered User
    Join Date
    Aug 2001
    Location
    Fort Worth, TX
    Posts
    53

    Question const on a function???

    I was looking at some C++ code and I notice that a function had const at the end of it. I have ask and ried to research, but haven't gotten a good answer for why you would use const that way. Example below.

    in header file

    int myFunction(int &i, const int j, const int x) const;


    in source file

    int myFunction(int &i, cont int j, const int x) const
    {

    do some stuff
    return val;
    }

    Why is there const at the end of the function and what will it gain you?

  2. #2
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    the const keyword at the end of a class method promises that that method won't change data members of the class. If ou try to do so after putting that keyword there, then the compiler should send an error or a warning.

  3. #3
    Seeking motivation... endo's Avatar
    Join Date
    May 2002
    Posts
    537
    that being the case th implementation of said function will look a bit like this:
    Code:
    int MyClass::myFunction(int &i, cont int j, const int x) const
    {
       do some stuff
       return val;
    }
    Couldn't think of anything interesting, cool or funny - sorry.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 12:45 PM
  2. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 01:13 AM
  3. Problem with Template Function and overloaded equality operator
    By silk.odyssey in forum C++ Programming
    Replies: 7
    Last Post: 06-08-2004, 05:30 AM
  4. structure vs class
    By sana in forum C++ Programming
    Replies: 13
    Last Post: 12-02-2002, 07:18 AM
  5. help: function returns typedef const
    By waddavis in forum C Programming
    Replies: 4
    Last Post: 12-11-2001, 10:19 AM

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