Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pointer and reference as return type in same function

Tags:

c++

So I was looking at some code and I came across this.

class Data{
 private:
  int data;
  Data* next;
 public:
   Data(int d=0): data(d), next(NULL) {}
   void SetData(int d) { data = d;}
   int  GetData() { return data; }
   Data*& GetNext() { return next; }
 }

The GetNext() return type is both the reference and pointer as return type. What does this mean?

like image 441
LaughingKid Avatar asked Apr 17 '19 19:04

LaughingKid


2 Answers

X * is a pointer to a X.

T & is a reference to a T. If T happens to be a pointer type, then it is a reference to a pointer: X* & is a reference to a X*.

As such, Data*& is a reference to a pointer to a Data.

like image 177
eerorika Avatar answered Sep 23 '22 16:09

eerorika


The value returned from GetNext() is a reference to a pointer to Data. This means it acts just like a pointer but if you change the value it will change the original object.

int main()
{
     Data*   d1 = new Data(1);
     std::cout << d1->GetData() << " : " << d1->GetNext()   // prints null;
               << "\n";

     d1->getNext() = new Data(2);   // Modify the value.

     std::cout << d1->GetData() << " : " << d1->GetNext()   // Does not print null
               << " -> " 
               <<  d1->GetNext()->GetData() << " : " << d1->GetNext()->GetNext()
               << "\n";
}
like image 37
Martin York Avatar answered Sep 21 '22 16:09

Martin York