Mastering Pointers and References in C++: Binding or Nesting Behaviors
A software developer must always pass the size of an object or array as a separate parameter when passing a pointer to a function and the whole object or array is copied in memory to a new scope; however, it is not necessary to pass the size as a parameter with a reference, and a reference does not require the entire object or array to be copied in memory. It takes considerably less space to pass a reference to a function than it takes to pass a pointer. References allow our programs to use quick functions instead of processing each item individually. It’s almost like using algebraic values instead of numeric values. Because pointers and references contain different structures, they are used for different purposes. A reference’s small size eliminates the size parameter making references best for functions that define and modify data structures with similar behaviors. Pointers that include a separate parameter indicating size works best for continuously changing behaviors that must be updated with the size parameter.
Pointers: Managing Adapting Behavior, Null Values, some APIs, Inheritance, Polymorphism
Instead of passing an entire string or array of data to a function, C++ passes the address of the location in memory, known as a pointer. Indexes allow a software engineer to pull specific values from an array. Because a function interprets an array as a place in memory, it needs to know the size of the array to access the indexes. This means that when we pass an array to a function, we must also pass the size of the array as a parameter in a separate variable. Pointers become a powerful tool when using null values, writing some APIs, implementing inheritance and polymorphism, or iterating through memory and manipulating dynamic memory.
References: Managing Data Structures with Similar Behaviors
References are often preferred for simplicity and readability, especially when working with arrays. Multidimensional arrays nest arrays within arrays, because they operate in a similar fashion using a reference is much cleaner than using a pointer. Data structures like vectors, matrices, grids, and tables work well with references, because they simulate a similar structure of behavior; whereas, inheritance, polymorphism, and iteration that work with changing behavior works best with pointers that acknowledge the size of the array.
Assessing the behaviors of a data structure allows a software developer to make strong choices when designing efficient, readable, and performant code.
Comments
Post a Comment