What is the dereference operator in C++?
Overview
In C++, the dereference operator * is used alongside a pointer ptr to obtain the value of a variable.
Note: Learn what pointers are here.
Example
#include <iostream>#include <string>using namespace std;int main() {// creating a variablestring name = "Theo";// declaring a pointerstring* ptr = &name;// obtaining the memory address of the variablecout << ptr << "\n";// Using the dereference operatorcout << *ptr << "\n";return 0;}
Explanation
- Line 7: We create a string variable
nameand assignTheoas its value. - Line 10: We create a pointer to this string variable.
- Line 13: We obtain and print the pointer
ptrwhich has the memory address of the variable. - Line 16: We print the value of
name.