Thread: returning reference from class

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    630
    Either
    Code:
    const std::string &str() const { return m_str; }
    or
    Code:
    std::string &str() const { return m_str; }
    Will give error: cannot convert from 'const std::string' to 'std::string &'

  2. #2
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by l2u View Post
    Either
    Code:
    const std::string &str() const { return m_str; }
    or
    Code:
    std::string &str() const { return m_str; }
    Will give error: cannot convert from 'const std::string' to 'std::string &'
    Well, sure. Inside a const function, all member variables act like they are const. So you can't return a non-const reference to a member from inside a const function. I don't believe you that the first example doesn't work. It should work fine.

  3. #3
    Registered User
    Join Date
    May 2006
    Posts
    630
    Quote Originally Posted by brewbuck View Post
    Well, sure. Inside a const function, all member variables act like they are const. So you can't return a non-const reference to a member from inside a const function. I don't believe you that the first example doesn't work. It should work fine.
    It does.. Sorry, I missed something

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  2. returning class and struct members
    By simone.marras in forum C++ Programming
    Replies: 17
    Last Post: 03-16-2009, 11:10 AM
  3. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  4. How can I pass a reference from a array os a class
    By Nautilus in forum C++ Programming
    Replies: 7
    Last Post: 01-20-2003, 06:23 AM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM