a shot of dev knowledge

RELATED TAGS

Differences between pointers and references in C++

A pointer in C++ is a variable that holds the memory address of another variable.

A reference is an alias for an already existing variable. Once a reference is initialized to a variable, it cannot be changed to refer to another variable. Hence, a reference is similar to a const pointer.

svg viewer

Key differences

Pointer

  • A pointer can be initialized to any value anytime after it is declared.

    int a = 5;
    // some code
    int *p = &a;
    
  • 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.

    Example:

    int a = 5;
    int *p;
    p = &a;
    int b = 6;
    p = &b;
    

Reference

  • A reference must be initialized when it is declared.

    int a = 5;
    int &ref = a;
    
    
  • 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.

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring