简体   繁体   中英

C++ How to pass reference to function

I have a class taking variables by reference. A function in the class needs to call another function that prints the object. The question arises when passing reference object from process() to disp() . Can I pass a reference from one function to another function? How to accomplish this using reference and what are best practices in such cases?

(I know one can take other approaches, such as using pointers or passing by value to class. But, I want to know solution with reference.)

class Abc
{
  double &a, &b;
public:

  Abc(double &var1, double &var2): a(var1), b(var2) {}

  void process()
  {
    //call disp()
    disp(a); //Question
  }

  void disp(double &var)
  {
    std::cout << var;
  }
};

int main()
{
  double x=2.2, y=10.5;
  Abc obj1(x,y);
  obj1.process(); //question
  return 0;
}

Can I pass a reference object to a function?

Pedantic point: There is no such thing as a "reference object". References are not objects.

But yes, it is possible to pass a reference to a function.

The question arises when passing reference object from process() to disp()

You already pass a reference there. That part of the program is correct.


You do have a problem here:

Abc::Abc(double&, double&);

float x=2.2, y=10.5 // anohter bug: probably intended to have a semicolon here
Abc obj1(x,y);

When object of one type ( float ) is bound to a reference of another type that is not related through inheritance ( double& ), the operand is converted to the target type ( double ). The result of the conversion is a temporary r-value. Non-const l-value references cannot be bound to r-values so therefore the program is ill-formed.

Even if the reference could be bound (for example, if you use a language extension that allows it, or if you used const references instead), the lifetime of the temporary would only extend for the lifetime of the reference variable which it was bound to, which is the argument of the constructor. After the constructor was finished, the member references would be referring to the temporary whose lifetime has already ended and therefore using those references would have undefined behaviour.

Simple solution: Use variables of same type as the reference: double x=2.2, y=10.5 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM