Creating Objects on the Heap

Just as you can create a pointer to an integer, you can create a pointer to any object. If you have declared an object of type Cat, you can declare a pointer to that class and instantiate a Cat object on the heap, just as you can make one on the stack. The syntax is the same as for integers:

Cat *pCat = new Cat;

This calls the default constructor—the constructor that takes no parameters. The constructor is called whenever an object is created—on the stack or on the heap.

Get Sams Teach Yourself C++ in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.