const at the end of a sub routine?

This is a discussion on const at the end of a sub routine? within the C++ Programming forums, part of the General Programming Boards category; Code: /** * Returns the name of the armor */ const string &Armor::getName() const { return name; } What does ...

  1. #1
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656

    const at the end of a sub routine?

    Code:
    /**
     * Returns the name of the armor
     */
    const string &Armor::getName() const {
        return name;
    }
    What does the const that's bolded mean? Would it be bad if I decided to delete that part of the code? YES, because the const object versions of the class will only be able to call that function, only if the compiler KNOWS that that function will not be editing its member variables. Saying 'const' promises to everyone that that function can be called by a const class object...knowing its vars will not be hurt during the process of the function being called.
    Last edited by Kleid-0; 10-23-2005 at 11:42 AM. Reason: Had to answer my question!

  2. #2
    Registered User
    Join Date
    Jun 2002
    Posts
    230
    the function getName() is a member function of class Armor right. Well that function doesnt appear to change anything in its body. Any member function that doesnt change any member variables must be declared const to gurantee that its not going to change anything. Im not 100% positive but if you take it out you should get a compiler error. Just remember any member function that doesnt change any member variables should be declared const.
    C++ Rules!!!!
    ------------
    Microsoft Visual Studio .NET Enterprise

  3. #3
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,801
    Woop?

  4. #4
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    Oohh man, I don't mean to sound stupid, but I can't grasp the concept of it. I'll do some self examples later and try rereading that tutorial. I'm an example kind of guy but the example in the tutorial didn't seem to explain what it was talking about to me, hmmm...

  5. #5
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    Code:
    const string &Armor::getName() const {
        return name;
    }
    I think the const there means that the function doesn't modify any variables.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  6. #6
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,801
    Fine then be lazy and stupid . Here is an example.
    Code:
    #include <iostream>
    
    class Test
    {
        public:        
            Test()
            {
                data = 10;
            }
            const int &getData()
            {
                return data;
            }
        private:
            int data;
    };
    
    void someFunc(const Test &toDo)
    {
        int a = toDo.getData();
    }
    
    int main()
    {
        Test mainTest;
    }
    This will not compile because the compiler doesn't know that you really aren't modifiying anything.
    Code:
    #include <iostream>
    
    class Test
    {
        public:        
            Test()
            {
                data = 10;
            }
            const int &getData() const
            {
                return data;
            }
        private:
            int data;
    };
    
    void someFunc(const Test &toDo)
    {
        int a = toDo.getData();
    }
    
    int main()
    {
        Test mainTest;
    }
    But this will compile because it knows you aren't modifying anything because you are saying this function does not modify anything
    Woop?

  7. #7
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    I don't think the compiler is required to enforce constness, but most do.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  8. #8
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,801
    I would doubt that. What would be the point of having const if the compiler doesn't have to support it? I don't have the standard around at this compie so I don't know for sure.
    Woop?

  9. #9
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    *scratches head*

    You know I think I'm getting to old for this
    I can't stop thinking about why a compiler would need this EVER, but somebody somewhere thought of it and I guess it has to make logical sense somehow...but I think the above should compile, gaaahhh....I guess..I'll try it tomorrow, but first I'm going to clean my room! I'll repost my data collection first thing tomorrow morning!

    Quote Originally Posted by prog-bman
    Fine then be lazy and stupid .
    Hey I'm only 2 years younger than you, so you better watch it!
    Last edited by Kleid-0; 10-22-2005 at 07:21 PM.

  10. #10
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    Any member function that doesnt change any member variables must be declared const to gurantee that its not going to change anything. Im not 100% positive but if you take it out you should get a compiler error.
    That's incorrect. A member function doesn't have to be declared const. It only has to be declared const if you want to call it with const objects. Of course, a const function cannot contain code that changes the object.

    Just remember any member function that doesnt change any member variables should be declared const.
    Now you got it.

    Would it be bad if I decided to delete that part of the code?
    Yes. Why do you want to delete it?

    The const at the end of a function means that the function is const. What does that mean? First, const after a function only has any relevance when you have a member function. You do not do this:
    Code:
    void greeting() const
    {
    	 cout<<"hello";
    }
    greeting() is not a member function.

    The const after a member function, like you have, says that the member function will not change the object that is calling the function. Changing the calling object would entail doing something like this:
    Code:
    const string &Armor::getName() 
    {    
        name = "Betty";
        return name;
    }
    That function changes the name member of the calling object. If a function is declared const, it cannot contain code that changes the calling object, and as a result the calling object can be an object that was declared const, e.g.:

    const Armor myArmor;

    Remember if an object is declared const, it is not allowed to be changed. If the member function did not have const after it, then an object that was declared const could not call the member function because a const object needs a guarantee that it won't be changed. A regular object has no such restriction, so a regular object can call a member function that does not have const after it. In that case, the member function can change the member variables of the object.

    Since you want as many objects of your class as possible to be able to call the member functions, you should declare any function as const when it doesn't need to change the calling object.
    Code:
    #include <iostream>
    using namespace std;
    
    class Apple
    {
    private:
    	int size;
    
    public:
    	Apple(int s=0)
    	{
    		size = s;
    	}
    
    	void display()  //no const
    	{
    		cout<<"size is: "<<size<<endl;
    	}
    
    	void show() const //const
    	{
    		cout<<"size is: "<<size<<endl;
    	}
    
    	void print() const //const function that attempts to change calling object
    	{
    		//size = 10; //error
                    
                    cout<<"size is: "<<size<<endl;
    	}
    
    };
    
    
    int main()
    {
    
    	Apple apple1(5);
    	const Apple apple2(10);
    
    	apple1.display();
    	//apple2.display(); //error
    
    	apple1.show();
    	apple2.show();
    
    	return 0;
    }
    Last edited by 7stud; 10-22-2005 at 10:22 PM.

  11. #11
    Registered User
    Join Date
    Jun 2002
    Posts
    230
    Simply put... in a class if the member function isnt changing any member variables the function should have a const.
    const just promises that your not changing anything thats all.
    C++ Rules!!!!
    ------------
    Microsoft Visual Studio .NET Enterprise

  12. #12
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    Thank you gamer4life687, 7stud (), prog-bman, and dwks.

    Well here's my report! http://killall.no-ip.org/const/

    I now know what the const means on the right side of a member function! It means that the function does not edit any variables of its class object, and thus can be called by const class objects of itself with that guarentee (that it won't edit itself!).

  13. #13
    Registered User
    Join Date
    Jun 2002
    Posts
    230
    Yup
    C++ Rules!!!!
    ------------
    Microsoft Visual Studio .NET Enterprise

  14. #14
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Why is there no mention that a const function can only call other const functions for the object?

  15. #15
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    * Am I ever going to use this?

    If for some crazy reason you're creating const class objects, like for just calling functions, not editing its variables explicitly, then you will need to know this.
    * Why make a class object const in the first place?

    To let yourself know and others know that that class is NOT meant to change anything with that object!
    To see a practical example of how a const object may come up in your code and trip you up--even though you didn't create a const object-- see this current thread:

    error C2678: binary '<'

    In that thread, a function parameter that was an object was declared const, e.g.

    void myFunc(const Armor& myArmor);

    As all experienced programmers know, you should declare parameters to functions as const if the function does not need to change the parameter. Inside a member function, an object, e.g. myArmor, was used to call another member function. That function call resulted in an error that the poster couldn't figure out. The object wasn't initially created as a const object, but by declaring the function parameter as const, it in effect said, "Inside this function the object will be treated as if it were a const object.". So, inside the function, the object could only call other member functions that were const, and the member function it was calling was not const.

    That raises a somewhat confusing issue about function parameters. A function parameter that is declared as const only says that inside the function the argument that is sent to the function will be treated as const. It does not require that you send a const variable to the function. Similarly, a reference type(&) in a function parameter does not require that you send the function a reference--it just says that inside the function the argument will be treated as a reference to the original variable(i.e. the original object can be changed). Therefore, the argument listed below matches both of the function parameters:
    Code:
    
    function parameter                         argument that can be sent to the function
    -------------------                             -----------------------
     void someFunc(Armor& anArmor);                      Armor myArmor;
     void someFunc(const Armor& anArmor);                Armor myArmor;
    With the last parameter declaration, you might notice a conflict: you are saying the argument is to be treated as a reference, which will allow you to change the original object, but the parameter also says the argument is to be treated as a const, which means you can't change the object. What happens? The result is: you are not allowed to change the object. Then why declare the parameter a reference? There are two advantages of declaring a parameter as a reference: 1) it allows you to change the original object, and 2) it means the compiler won't have to make a copy of the original object for the function, unlike when you "pass by value". Advantage 1) is negated by the const declaration for the parameter, but advantage 2) still applies.


    * Why can't you have const in front of a nonmember function?

    Because it's only to prevent OBJECTS from being changed, the variables within an object by a member function. The const outside of a function is a special warden against consts of its inner self, nonmember functions have their own protection against editing constant values, such as private vars, and instantly knowing that the var is "constant". While when you're dealing with this member problem, the "constant" is outside of the class, and so there's a special warden of putting a const to the right side of those functions to allow them into the class object.
    I can't make any sense of that. The reason const is needed for member functions is that every member function has an invisible parameter that is passed to the function: the this pointer. The this pointer is what is used to change an object:

    name = "Betty";

    is equivalent to:

    this->name = "Betty";

    You can write the latter inside a function and it will do the same thing. When you declare a member function const, you are telling the compiler to treat the this pointer as pointer to a constant.
    Last edited by 7stud; 10-23-2005 at 09:34 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem building Quake source
    By Silvercord in forum Game Programming
    Replies: 16
    Last Post: 07-11-2010, 09:13 AM
  2. Smart pointer class
    By Elysia in forum C++ Programming
    Replies: 63
    Last Post: 11-03-2007, 07:05 AM
  3. matrix class
    By shuo in forum C++ Programming
    Replies: 2
    Last Post: 07-13-2007, 01:03 AM
  4. "error: incomplete type is not allowed"
    By Fahrenheit in forum C++ Programming
    Replies: 9
    Last Post: 05-10-2005, 09:52 PM
  5. Memory leak - need help finding
    By ChadJohnson in forum C++ Programming
    Replies: 8
    Last Post: 04-06-2005, 07:26 PM

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