I have this code, but it is not a practical example.
Ex.
class Animal
{
   int i;
   int& ref;
   public:
   Animal() : ref(i)
   {
   }
};
Can anyone provide a real life example where ref is required as a class member so that I can understand it better?
Any time that multiple objects of some class A all need to refer to a single shared instance of the same or some other class; for example, several People can all have the same mother and/or father:
class Person {
    private:
      Person &mother_;
      Person &father_;
    public:
      Person(Person &mother, Person &father) : mother_(mother), father_(father) {}
      // ...
}
Sure: The whole purpose of the template class std::reference_wrapper<T> is to hold a reference!
This has many uses. For example, you can pass it to the std::thread constructor (which always makes copies). You can also make containers of reference-wrappers.
Holding a reference to something might also be useful when you want to wrap an output stream; you hold the original stream as a reference and add things to it (for example, this answer of mine could be improved by adding a reference to the underlying stream to the wrapper objects).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With