Struct problems

This is a discussion on Struct problems within the C++ Programming forums, part of the General Programming Boards category; This is supposed to return the sum of inches and feet within strucst. Why won't this work? *Attempting to return ...

  1. #1
    Registered User
    Join Date
    Oct 2002
    Posts
    155

    Struct problems

    This is supposed to return the sum of inches and feet within strucst. Why won't this work? *Attempting to return a reference to local variable "tempDist"* error

    Code:
    englishDist &operator +(englishDist distances1, englishDist distances2){
    	englishDist tempDist;
    
    	double feet = distances1.feet + distances2.feet,
    		   inches = distances1.inches + distances2.inches;
    	double temp = fmod(inches, 12.0);
    	
    	tempDist.feet = int(feet + ((inches - temp) / 12.0));
    	tempDist.inches = temp;
    	return tempDist;
    } //end englishDist &operator +

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    Exactly what the message says. You can't return a reference to a local object, since it goes out of scope when the function ends.

    Either return the object itself instead of a referense to it, or declare the local object as static (but this can have weird side effects if you call this function multiple times).
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  3. #3
    Registered User
    Join Date
    Oct 2002
    Posts
    155
    I try both those methods and I get garbled data

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Converting from C to C++
    By Taka in forum C++ Programming
    Replies: 5
    Last Post: 04-08-2009, 03:16 AM
  2. Replies: 1
    Last Post: 12-03-2008, 03:10 AM
  3. weird typedef struct problems
    By olidem in forum C Programming
    Replies: 3
    Last Post: 07-28-2008, 03:59 PM
  4. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 04:00 PM
  5. towers of hanoi problem
    By aik_21 in forum C Programming
    Replies: 1
    Last Post: 10-02-2004, 02:34 PM

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