Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of having a class member that is a ref type? [closed]

Tags:

c++

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?

like image 540
user966379 Avatar asked Dec 17 '11 03:12

user966379


2 Answers

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) {}
      // ...
}
like image 151
Ernest Friedman-Hill Avatar answered Oct 04 '22 23:10

Ernest Friedman-Hill


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).

like image 29
Kerrek SB Avatar answered Oct 04 '22 21:10

Kerrek SB