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 variable
string name = "Theo";
// declaring a pointer
string* ptr = &name;
// obtaining the memory address of the variable
cout << ptr << "\n";
// Using the dereference operator
cout << *ptr << "\n";
return 0;
}

Explanation

  • Line 7: We create a string variable name and assign Theo as its value.
  • Line 10: We create a pointer to this string variable.
  • Line 13: We obtain and print the pointer ptr which has the memory address of the variable.
  • Line 16: We print the value of name.

Free Resources