Thread: const on a function???

  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, 11:45 AM
  2. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12: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, 04: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