Whats wrong??

This is a discussion on Whats wrong?? within the C++ Programming forums, part of the General Programming Boards category; private: string mySender; string temp; mySender and temp declared as string. I still couldnt figure out whats wrong with my ...

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    41

    Whats wrong??

    private:
    string mySender;
    string temp;


    mySender and temp declared as string. I still couldnt figure out whats wrong with my following code ??

    Code:
    string Message::getMessage() const {
    	temp = mySender;
    
    	return mySender;
    }

  2. #2
    Registered User
    Join Date
    May 2003
    Posts
    82
    If temp is a member variable, your getMessage function changes the state of the object, thus it can't be const.

    This should compile, although you might want to reconsider the logic of your class. I would consider a non-const function prefaced with "get" somewhat misleading.

    Code:
    string Message::getMessage() {
    temp = mySender;
    
    return mySender;
    }

  3. #3
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Well, you can modify member data in a const function if the member data is declared as mutable. This, however, should be reserved for very special cases when the function is logically const (logically does not change the object), but may need to set a flag (for example, counting how many times a certain piece of data has been accessed).

    And, for future reference, it helps if you post what errors/problems you get along with the code.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 07-15-2004, 03:30 PM
  2. Debugging-Looking in the wrong places
    By JaWiB in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 11-03-2003, 09:50 PM
  3. Confused: What is wrong with void??
    By Machewy in forum C++ Programming
    Replies: 19
    Last Post: 04-15-2003, 12:40 PM
  4. God
    By datainjector in forum A Brief History of Cprogramming.com
    Replies: 746
    Last Post: 12-22-2002, 11:01 AM
  5. Whats wrong?
    By Unregistered in forum C Programming
    Replies: 6
    Last Post: 07-14-2002, 01:04 PM

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