Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is a reference variable appropriate and why? Can you explain the actual syntax and placement? [duplicate]

I am brand new to C++. We have recently begun exploring reference variables in class, and I am very confused about them. Not necessarily how to do them, as I understand that they switch variable values, but more along the lines of WHY a developer would want to do such a thing? What do they accomplish? Do they save memory? Do they avoid having to return information?

Here is part of the project we are working on. We need to include at least one reference variable. I can see how I would write the program without the reference variable, but I don't see where a reference variable would be useful or necessary.

"The user may wish to get an estimate for one to many rooms. The rates are based on the square footage of the walls and/or ceiling. The company estimates that it takes 2.5 hours to paint 200 SF of wall space and 3.2 hours to paint the same area on a ceiling. The labor rate is $40 per hour. If the job for painting WALLS totals more than 1400 SF of space, then the customer receives a 15% discount for all square footage above 1400 square feet. There is no discount for painting ceilings.

The program shall print out a final report of the estimated costs in a professional format.

The program shall ask the user if they want to make more calculations before exiting."

I'm not looking for you guys to do my homework for me, and for reference, we have only just finished with learning functions. I'm pretty good, but there are a LOT of things reading through these sites that I do not understand.

And, essentially, studentID would be set to 21654. Am I understanding this correctly?

Let us try this again:

I have reviewed this suggested duplication. While it does cover the basics of the pros/cons of using reference variables instead of pointers and discusses multitudes of reasons for using both, I am still questioning the basic idea of when (when is is appropriate vs. not necessary) and why (why is appropriate in certain circumstances, what advantages does it give to the program?)

I should use such variables as well as how (the actual syntax and placement). Almost everyone here has been great, and I have learned so much on the subject through my interactions with you. Even as much of this is repetitive and irritating to seasoned coders, it is all new to me, and I needed to be involved in the conversation as much as I needed the information. I have used Stack Overflow for many projects, learning about Java's newString.equalsIgnoreCase(), for instance, and I admire your knowledge. I can only tell you the truth, if that is not good enough then it is what it is.

Alright, let me review my understanding so far:

Reference variables tend to cut down on unwanted modification of variables within a function and/or program.

Reference variables are used to modify existing variables within functions

This is useful as it "moves" values around while minimizing copying of those values.

Reference variables modify existing variables within functions/programs

I don't know if you guys can still read this or not since it has been flagged a duplicate. I've been playing with a few of the mini-programs you guys have given me, re-read portions of my book, done further research, etc., and I think I understand on a rudimentary level. These reference variables allow you to alter and/or use other variables within your code without pulling them directly into your code. I can't remember which user was using the foo(hubble, bubble) example, but it was his/her code that finally made it click. Instead of just using the value, you are actually using and/or reassigning the variable.

like image 495
Eryn Avatar asked Oct 27 '17 06:10

Eryn


2 Answers

A reference variable is nothing but an alias name of the variable. You would use it when you wanted to just pass the value around instead of copying the same variable into memory at a different location. So, using reference, copy can be avoidable which saves the memory.

According to Bjarne Stroustrup's FAQ:

C++ inherited pointers from C, so I couldn't remove them without causing serious compatibility problems. References are useful for several things, but the direct reason I introduced them in C++ was to support operator overloading. For example:

void f1(const complex* x, const complex* y)    // without references
    {
        complex z = *x+*y;    // ugly
        // ...
    }

    void f2(const complex& x, const complex& y)    // with references
    {
        complex z = x+y;    // better
        // ...
    }

More generally, if you want to have both the functionality of pointers and the functionality of references, you need either two different types (as in C++) or two different sets of operations on a single type. For example, with a single type you need both an operation to assign to the object referred to and an operation to assign to the reference/pointer. This can be done using separate operators (as in Simula). For example:

Ref<My_type> r :- new My_type;
r := 7;            // assign to object
r :- new My_type;    // assign to reference

Alternatively, you could rely on type checking (overloading). For example:

Ref<My_type> r = new My_type;
r = 7;            // assign to object
r = new My_type;    // assign to reference

Also, read this Stack Overflow question about the differences between a pointer variable and a reference variable.

like image 75
msc Avatar answered Sep 19 '22 15:09

msc


I will give three reasons, but there are many more.

  1. Avoiding unnecessary copies.

    Suppose you write a function like so:

    double price(std::vector<Room> rooms)
    {
           ...
    }
    

    Now, every time you call it, the vector of Room will be copied. If you only compute the prices of a few rooms that's fine, but if you want to compute the cost of repainting the entirety of the offices of the Empire State Building, you will start to copy huge objects, and this takes time.

    It is better in this case to use a constant reference that provides read-only access to the data:

    double price(const std::vector<Room>& rooms) { ... }
    
  2. Using polymorphism

    Suppose you now have different types of rooms, perhaps a CubicRoom and a CylindricalRoom, that both inherit from the same base class, Room.

    It is not possible to write:

    double price(Room room) { ... }
    

    and then call

    price(CylindricalRoom());
    //or
    price(CubicRoom());
    

    but you can if you define price as follows:

    double price(Room& room);
    

    Everything then works the same as if you passed by value.

  3. Avoiding returns

    Suppose that each time you compute a price, you want to add a formatted quote to a report. In C++ you can only return a single object from a function, so you can not write:

    return price, fmtQuote
    

    However, you can do:

    double price(Room room, std::vector<std::string>& quotes)
    {
        ...
        quotes.push_back(fmtQuote);
        return price
    }
    

    Obviously, you could return a pair of objects std::pair<double, std::string>, but this means that the caller has to unpack the result. If you intend to call often the above function, this will quickly become ugly. In this case, this ties in to the first point: the log of all quotes will grow, and you do not want to copy it for each call.

    This is a typical access pattern for shared resources: you want a few functions/objects to get a handle on a resource, not a copy of that resource.

like image 30
Urukann Avatar answered Sep 19 '22 15:09

Urukann