Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 334
  • Last Modified:

Class reference

I have a class defined as follows:
What is the use case of having a reference. it is so confusing :(

class Base
   public:
        class Inner {
              Base& _base;
              public:
                  Inner(Base& in);
         };
};

Base::Inner::Inner(Base& in) 
     : _base(in) {}

Open in new window

0
perlperl
Asked:
perlperl
  • 2
1 Solution
 
jkrCommented:
There could be a lot of reasons for such a construct, with the most likely one being to 'link' two specific objects together. Why that is done in your case is quite hard to tell from just that snippet. The must be a reason for 'Inner' to interact with a 'Base' object it is related to.
0
 
jkrCommented:
BTW, something more basic about references and how they are used: http://en.wikipedia.org/wiki/Reference_%28C%2B%2B%29
0
 
sarabandeCommented:
a reference member needs to be provided at construction time. so, contrary to a pointer member, the object referenced by the member has to exist at construction time of the Inner object (and would need to keep valid thru lifetime of the Inner object).  

as the Inner class is defined within Base class, it is even likely that the Base reference would be a reference to the own parent Base object.

class Base
{
   public:
        class Inner {
              Base& _base;
              public:
                  Inner(Base& in);
         };
        Base();
   private:
       Inner _inner;
};

Base::Inner::Inner(Base& in) 
     : _base(in) {}

Base::Base()
    : _inner(*this) {}

Open in new window


such a construction could be used for to encapsulate all major functionality in the Inner class and to offer only a minimal public interface for the class itself.

Sara
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now