-
Notifications
You must be signed in to change notification settings - Fork 27
Refrence instead of Pointer
Ali Mahdiyar edited this page Nov 16, 2018
·
3 revisions
We try to avoid using pointers in c++ and replace it with references and iterators. Consider the following code:
#include <iostream>
#include <vector>
using namespace std;
class A{
public:
A(int x){
this->x = x;
}
int x;
};
vector<A> items;
A* f(){
return &items[0];
}
int main(){
items.push_back(A(3));
A* item = f();
item->x = 5;
cout << items[0].x << endl; // prints 5
return 0;
}
Now we can use it this way:
...
A& f(){
return items[0];
}
int main(){
items.push_back(A(3));
A& item = f();
item.x = 5;
cout << items[0].x << endl; // prints 5
return 0;
}
-That's why we avoided using User* return type for signup and used User&.