with C++ Lecture 20
References and Pointers
1. Overview
o C++ supports both references and pointers, allowing for
flexible memory management and function parameter
passing.
o Reference: An alias for another variable, which cannot be
null, must be initialized, and cannot be reassigned.
o Pointer: Stores the address of a variable, which can point to
different objects or be null during its lifetime.
2. Advantages of References
o Safer than pointers as they must always refer to a valid
object.
o No need for dereferencing operators to access the value,
making the code cleaner.
Example:
, 3. When to Use Pointers
o Pointers are necessary when dealing with dynamic memory
allocation, arrays, and situations where the object being
pointed to may change during runtime.
Example:
Polymorphism with References (from C++11)
1. Polymorphism with Virtual Functions
o Polymorphism allows calling the correct function version based
on the object's type at runtime, even when accessed through
a base class reference.
Example: