Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Pointer to reference and Pointer to the actual variable be treated as same?

Tags:

c++

reference

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.
like image 418
aJ. Avatar asked Jan 08 '10 11:01

aJ.


2 Answers

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.

like image 98
Andreas Brinck Avatar answered Sep 30 '22 20:09

Andreas Brinck


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

like image 32
jk. Avatar answered Sep 30 '22 20:09

jk.