tags:

views:

132

answers:

3

I recently saw the below code ( simplified version given below) in my code base and got this doubt:

class B;
class A
{
  public:
     A():m_A("testA"){}
     B& getB()
     {
       return m_B;
     }
     B* getBPtr() //== > written to explain the problem clearly
     {
       return &m_B;
     }
private:
    B m_B;
};

class B
{
  public:
    B(const std::string& name):m_Name(name){}
    std::string getName() const
    {
      return m_Name;
    }
private:
    std::string m_Name;
};

class C
{
 public:
   void testFunc(B* ptr)
   {
   }
};


int main()
{
  A a;
  C c;
 c.testFunc(&a.getB()); ===> is it equivalent to c.testFunc(a.getBPtr()) ?
}
  1. The pointer to reference and pointer to actual variable can be treated as same?
  2. Does standard says anything on the address of reference to be interchangeable used for address of variable.
+2  A: 

Yes, it's not possible to take the address of a reference. You always get the address of the referred object.

jk
+2  A: 

Yes it is equivalent. Taking the address of a reference returns the address of the original thing. Since there is no way to get any other address out of a reference, there is no seperate type for a pointer to a reference.

Michael Anderson
+8  A: 

First sentence of standard 8.3.2/4:

There shall be no references to references, no arrays of references, and no pointers to references

(My emphasis)

This doesn't mean you can't take the address of a variable declared as a reference, it just means that there's no separate type for a pointer to a reference.

Andreas Brinck
I'm glad you clarified that. ;-)
Richard Pennington
Hmmm... I am still confused with the line from standard. I was interpreting that line from standard as ---- we should not try to take pointers to reference. means, address of the reference must not be used.
aJ
Andreas Brinck
It sort of does mean you can't take the address of a reference. You can use a reference to take the address of its referand, but you can't take the address of a reference itself. References are not objects, and don't have addresses.
Steve Jessop
@Steve Yes, that's what I meant. I've edited my answer.
Andreas Brinck
Bonus. I had already upvoted you anyway, though :-)
Steve Jessop
smerlin