It is a variable that behaves as an alias for another variable. They are created using the ampersand (&) operator. When we create a variable, then it occupies some memory location. We can create a reference of the variable; therefore, we can access the original variable by using either name of the variable or reference
CODE:
//Example 1
int a=10;
int &ref=a;
//Example 2
int a=10; // 'a' is a variable.
int &b=a; // 'b' reference to a.
int &c=a; // 'c' reference to a.
- Must be initialized during declaration.
- Cannot be reassigned
- Can also be passed as a function parameter.
Now let’s see the key differences between references and pointers:-
POINTERS
- A pointer can be initialized to any value anytime after it is declared.
- A pointer can be assigned to point to a NULL value.
- Pointers need to be dereferenced with a *
- A pointer can be changed to point to any variable of the same type.
REFERENCES
- A reference must be initialized when it is declared.
- References cannot be NULL.
- References can be used ,simply, by name.
- Once a reference is initialized to a variable, it cannot be changed to refer to a variable object.
In the final topic for this video, we will understand that a function pointer is a pointer used to point functions. It is used to store the address of a function. We can call the function by using the function pointer, or we can also pass the pointer to another function as a parameter.
They are mainly useful for event-driven applications, callbacks, and even storing functions in arrays.
void printname(char *name)
{
std::cout << "Name is :" <<name<< std::endl;
}
int main()
{
char s[20];
void (*ptr)(char*); // function pointer declaration
ptr=printname; // storing the address of printname in ptr.
std::cout << "Enter the name of the person: " << std::endl;
cin>>s;
cout<<s;
ptr(s);
return 0;
}