Thread: Conversion error

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    65

    Conversion error

    Code:
    int& test(const int& i) {return i;}
    In VC++ I get a compiler error "error C2440: 'return' : cannot convert from 'const int' to 'int &'". I don't know why this is an error, it's just a function taking a const int reference and then returning it. i is not being changed.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    You are not allowed to remove const-ness. You could return a const int &, or do a const_cast if you actually know that it's the right thing to do.

  3. #3
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    This function in itself is pointless, but here are some of your options:
    Code:
    const int& test(const int& i) {return i;}
    int& test(int& i) {return i;}
    int test(const int& i) {return i;}
    You could also use const_cast as tabstop suggested, but for this type of function I think that would be purely evil and dangerous because you can't control how that int& is used once it leaves your function.

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by jw232 View Post
    Code:
    int& test(const int& i) {return i;}
    In VC++ I get a compiler error "error C2440: 'return' : cannot convert from 'const int' to 'int &'". I don't know why this is an error, it's just a function taking a const int reference and then returning it. i is not being changed.
    The compiler is complaining that i is const, and you are returning a non-const reference to it, which means that someone else can access the variable freely - so you are "loosing" the const.

    You probably don't actually want to do that, and the suggestions from cpjust shows you some valid alternatives that will all work.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Quantum Random Bit Generator
    By shawnt in forum C++ Programming
    Replies: 62
    Last Post: 06-18-2008, 10:17 AM
  2. more then 100errors in header
    By hallo007 in forum Windows Programming
    Replies: 20
    Last Post: 05-13-2007, 08:26 AM
  3. Using VC Toolkit 2003
    By Noobwaker in forum Windows Programming
    Replies: 8
    Last Post: 03-13-2006, 07:33 AM
  4. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  5. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM