1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Const int & method (int & parameter)

  1. Sep 14, 2008 #1
    dec is a method that gets the parameter by reference, changes its value and returns a reference const int.

    Problem [in bold]: In the book it says, "const means that that the object being returned cannot itself by modified later on." But, I changed the return value without any error.

    Code (Text):
    #include <iostream>
    using namespace std;

    const int & dec (int & a)
        a = 5;
        return a;

    int main()
        int a = 0;
        cout<<"a = "<<a<<endl;
        cout<<"Passing to the method ... "<<endl;
       [B] int b = dec(a);
        b = 6; //***I am chaning the returned type value****[/B]
        cout<<"a = "<<a<<" b = "<<b<<endl;
        cout <<"Chaning a value ... "<<endl;
        a = 6;
        cout<<"a = "<<a<<endl;
        cout<<"Passing to the method ... "<<endl;
        b = dec(a);
        cout<<"a = "<<a<<" b = "<<b<<endl;
  2. jcsd
  3. Sep 14, 2008 #2


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    No you didn't: you changed b. b is not the return value of your function; it is merely an int value which was initialized to be a copy of the return value of your function.
    Last edited: Sep 14, 2008
  4. Sep 14, 2008 #3
    oook thnx!
    So, I was using operator = which makes a deep copy.

    This throws error now that I cannot change const value ...
    dec(a) = 5;

    And that's why book was recommending to use

    const int & b = dec(a);
    rather than
    int b =dec(a);

    so that I avoid cost of copying.
  5. Sep 14, 2008 #4


    User Avatar
    Homework Helper

    old versions of fortran were always fun with stuff like this:

    call example(1.0)
    b = 1.0
    c = b+1.0


    subroutine example(a)
    a = 2.0

    Yep no checking for changing of constants.
  6. Sep 14, 2008 #5
    What is the cost of copying ?
  7. Sep 14, 2008 #6
    I was talking about complex objects where you perform several operations to make the object copy like deleting all the pointers .. and then providing them new locations:

    I need to override something like this function..
    const & Object operator:= (const Object &rhs)

Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?

Similar Discussions: Const int & method (int & parameter)
  1. FORTRAN REAL*INT error (Replies: 2)

  2. Why are Ints 32 bits? (Replies: 8)