0

I have written the following member function of a class Point

    double  &Function(){
     double d=33.66;
     double *p=new double;
     p=&d;
     return *p;
    }

which is being called in the main () using Point object "pt" as, pt.Function(). This works, although I don't quite understand why? Can it be improved? I know this is not the best way to get the value of "d" but I use it to learn how to pass values using reference. Thanks for your help.

OPP
  • 1
  • Your function is 4 lines long, and has 2 major issues. Impressive. – StoryTeller - Unslander Monica Nov 29 '17 at 07:12
  • You don't *pass* by reference. *Passing* is what happens to *arguments* of functions when being called. You *return* a reference. And you return a reference to a variable that will go out of scope once the function returns, and therefore will cease to exist, leaving you with a reference to something that doesn't exist. Perhaps you should take a couple of steps back, [get a good beginners book or two](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), and start over. – Some programmer dude Nov 29 '17 at 07:16
  • Thanks for the clarification. I for sure need to learn c++. – OPP Nov 30 '17 at 17:29

2 Answers2

0
 p=&d;

Here, It's just creating a memory leak. You will never get to use that allocated memory in this instance of the program.

msc
  • 33,420
  • 29
  • 119
  • 214
0

You do not need to return the value of a POD (Plain Old Data) local variable, which is d in your case by reference. You can simply return it by value.

A possible scenario where you will need to return something by reference is when the value is a member of your class, and you need to modify it from somewhere else.

Example:

// Declaration
class Point {
private:
    double _d = 33.66;
public:
    double& getD() { return _d; }
}

// Usage
Point p;
p.getD() = 66.33;
acidleaf
  • 21
  • 4
  • Thanks for the answers and comments. I am new to c++. By the way, can I not return a non-member variable "d" using function getD()? – OPP Nov 30 '17 at 17:28
  • If you return a reference to a local variable, that reference would become invalid as soon as the local variable's lifetime ends, which is after the function returns. Trying to access that reference would cause undefined behavior. – acidleaf Dec 04 '17 at 06:56