While you can create pointers with ordinary primitive objects, that’s not where the real power of pointers lie. The power is to reference objects that we create, so they don’t take up too much space in lower memory locations, and we can work on passing them around.
To create an object dynamically on the heap, you use the new keyword, such as below:
Circle* circle1 = new Circle(5);
Circle* circle2 = new Circle();
Circle* circle3 = new Circle;
The last two create the Circle object with no arguments. The first example, shows it being created with arguments.
This allows you to create objects and manage local memory better by storing only the pointer in the lower memory range, and the object itself in higher portions so you won’t run out of memory space.
However, it means you cannot access the object’s properties and methods as easily. You either need to dereference the object, or use the arrow operator as shown in the example below. The arrow operator is the most common method as it’s a little easier and faster to write.
cout << "The area is " << (*circle1).getArea() << endl;
cout << "The area is " << circle1->getArea() << endl;
If you remember when we talked about returning a pointer from a function, I said at that point it served little purpose. However, being able to create a new object, and return it from a function has a lot of uses and power.
Creating and Accessing Dynamic Objects in C++ was originally found on Access 2 Learn
One Comment
Comments are closed.