lundi 5 février 2018

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 object to a 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()
{
Abc obj1(2.2,10.5);
obj1.process(); //question
return 0;
}

Aucun commentaire:

Enregistrer un commentaire