Summary - Why use pointers:
Pointers are used in C++ for several reasons:
Dynamic memory allocation: Pointers allow you to dynamically allocate memory at run-time, which is useful when you don't know the size of the data you'll need in advance. For example, if you're reading data from a file, you may not know how much memory to allocate until you've read the data. Pointers allow you to allocate the necessary memory at run-time and work with the data indirectly.
Passing arguments by reference: Pointers allow you to pass arguments to functions by reference, rather than by value. Passing arguments by reference allows the function to modify the original data directly, rather than creating a copy of the data, which can be more efficient and reduce memory usage.
Working with arrays: Pointers allow you to work with arrays directly by using pointer arithmetic. When you define an array, you're actually defining a pointer to the first element of the array. Using pointer arithmetic, you can access the other elements of the array indirectly.
Object-oriented programming: Pointers are used extensively in object-oriented programming to work with objects indirectly. When you define an object, you're actually defining a pointer to the object. Using pointer arithmetic and polymorphism, you can work with objects of different types indirectly.
However, working with pointers requires careful management of memory to avoid memory leaks and other errors. You must ensure that you allocate and deallocate memory properly, and that you don't access memory that has already been deallocated.
Pointers used to call class member functions
When a class member function is called on an object, a pointer to the object is automatically passed to the member function as an implicit parameter called the this pointer. The this
pointer enables access to an object's data members within the object's class member functions. A data member can be accessed using this
and the member access operator for a pointer, ->
,ex. this->sideLength
. The this
pointer clearly indicates that an object's data member is being accessed, which is needed if a member function's parameter has the same variable name as the data member.
Recall from the previous section on Objects and Classes When a class member function is called on an object, a pointer to the object is automatically passed to the member function as an implicit parameter called the this pointer. The this
pointer enables access to an object's data members within the object's class member functions. A data member can be accessed using this
and the member access operator for a pointer, ->
,ex. this->sideLength
. The this
pointer clearly indicates that an object's data member is being accessed, which is needed if a member function's parameter has the same variable name as the data member.-> The 'this' implicit parameter