Returning address to temp var.

This is a discussion on Returning address to temp var. within the C++ Programming forums, part of the General Programming Boards category; Hi. I recently wrote a matrix class and overloaded the '()' operator for easy access to the elements. I return ...

  1. #1
    Registered User
    Join Date
    Nov 2002
    Posts
    10

    Returning address to temp var.

    Hi.

    I recently wrote a matrix class and overloaded the '()' operator for easy access to the elements. I return the address of the selected element for easy modification.

    Then I also thought that you might wanna make the element read-only, anyway this was my solution :

    Code:
    double & CMatrix::operator () (int row, int col)
    {
    	//Err check omitted	
    
    	if (readOnly)
    	{
    		double tempVal = elements[row][col];
    		return tempVal;
    	}
    	
    	return elements[row][col];
    }
    I get a warning when I compile (returning address of local variable...) but I don't know if this would be bad/dangerous in this particular case.

    Is this a bad way to do it in this case ? If so why, and what would be a better solution ?

  2. #2
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,088
    Yes, this is a bad solution because the tempVal variable will go out of scope and a reference to garbage will be returned.

    A better way to return read-only might be to make a separate function that is const and returns a const reference. That way you have two functions, one that is read-only and one that isn't. The compiler will figure out which one to use as appropriate.

  3. #3
    Registered User
    Join Date
    Mar 2004
    Posts
    1
    You could create two seperate overloads, one that returns the value (and therefor read only) and another that returns a reference to the value in the class.

    Returning a reference to a local variable is worthless as it is likely a garbage value as soon as the function goes out of scope.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help assignment
    By 6kaine9 in forum C Programming
    Replies: 26
    Last Post: 10-19-2008, 08:51 PM
  2. server question
    By xddxogm3 in forum Tech Board
    Replies: 24
    Last Post: 01-21-2004, 12:12 AM
  3. linked list recursive function spaghetti
    By ... in forum C++ Programming
    Replies: 4
    Last Post: 09-02-2003, 02:53 PM
  4. explain linked lists returning a node address
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 12-11-2001, 08:53 PM
  5. Returning address of pixel...
    By Cheeze-It in forum Game Programming
    Replies: 14
    Last Post: 08-27-2001, 05:57 PM

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