220 likes | 605 Views
C++ Reference Variables:. References must be initialized. int x; int& foo = x; // foo is now a reference to x so this sets x to 56 foo = 56; cout << x <<endl;.
E N D
References must be initialized. int x; int& foo = x; // foo is now a reference to x so this sets x to 56 foo = 56; cout << x <<endl;
References save copying of objects when passed as arguments to functions. So we get efficiency gain with references. This is possible with pointers also.
References vs Pointers It is not possible to refer directly to a reference object after it is defined; any occurrence of its name refers directly to the object it references. Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers. References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid. Note that for this reason, containers of references are not allowed. References cannot be uninitialized. Because it is impossible to reinitialize a reference, they must be initialized as soon as they are created.
References are better than pointers a) Safer b) Easier to use
An example of reference #include<iostream>using namespace std;void swap (int& first, int& second){ int temp = first; first = second; second = temp;}int main(){ int a = 2; int b = 3; swap( a, b ); cout<<a<<" "<<b; getchar(); return 0;}
Functions should not return reference to local variables // Invalid codeint& getLocalVariable(){ int x; return x;} What if we make x static?
Scope Resolution Operator #include<iostream>using namespace std; int x = 10;void fun(){ int x = 2; { int x = 1; cout << ::x << endl; }}int main(){ fun(); getchar(); return 0;} Output: 10 Similarly scope resolution operator can be used to access global functions
#include<iostream> using namespace std; class Point { private: int x; int y; Public: // Constructor Point(int i, int j) { x = i; y = j; } // Methods int getX() { return x; } int getY() { return y; } };
// A function that takes two point objects as parameter and returns a new // point object Point addPoints(Point &p1, Point &p2) { Point t(p1.getX()+p2.getX(), p1.getY()+p2.getY()); return t; } int main() { Point obj1(12, 13); Point obj2(8, 10); Point obj3 = addPoints(obj1, obj2); cout<<"x coordinate of obj3 = "<<obj3.getX()<<"\n"; cout<<"y coordinate of obj3= "<<obj3.getY(); return 0; } Output: x coordinate of obj3 = 20 y coordinate of obj3= 23