Deborah R. Fowler
OOP Pointers for
C++
Posted on Oct 19 2019Updated Oct 20 2019
This section assumes you have read the basics of OOP for C++
POINTERS
A pointer stores the memory address of another value
located in memory. That "value" could be an object for example.
When we try to get to the value of the object pointed to it is
referred to as *dereferencing.
Reminder that & represents an address and *
represents a pointer type or de-reference. An empty pointer can be
assigned the value NULL.
https://en.wikipedia.org/wiki/Pointer_(computer_programming)
For example:
By why would we want to do this? Well, we are unlikely to do this for an integer values, but image if you were using a data structure that was larger and wanted to pass it to a function? More efficient to give it the address than make another copy.
Because pointers are required for polymorphism, C++ has provided an excellent way to create objects/instances of classes using the function "new".
So suppose we have a class, now this would look like:
This will print "Hello, I'm a muppet" three times. Once for kermit.talk() and then twice for probin. probin is a pointer to an instance (object) of class Muppet.
Next up - Inheritance