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?
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.
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With