Sams Teach Yourself C++ in 21 Days

(singke) #1

Creating Objects on the Free Store......................................................................


Just as you can create a pointer to an integer, you can create a pointer to any data type,
including classes. If you have declared an object of type Cat, you can declare a pointer to
that class and instantiate a Catobject on the free store, 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 con-
structor is called whenever an object is created (on the stack or on the free store). Be
aware, however, that you are not limited to using only the default constructor when creat-
ing an object with new—any constructor can be used.

Deleting Objects from the Free Store ..................................................................


When you call deleteon a pointer to an object on the free store, that object’s destructor
is called before the memory is released. This gives your class a chance to clean up (gen-
erally deallocating heap allocated memory), just as it does for objects destroyed on the
stack. Listing 8.5 illustrates creating and deleting objects on the free store.

LISTING8.5 Creating and Deleting Objects on the Free Store
1: // Listing 8.5 - Creating objects on the free store
2: // using new and delete
3:
4: #include <iostream>
5:
6: using namespace std;
7:
8: class SimpleCat
9: {
10: public:
11: SimpleCat();
12: ~SimpleCat();
13: private:
14: int itsAge;
15: };
16:
17: SimpleCat::SimpleCat()
18: {
19: cout << “Constructor called. “ << endl;
20: itsAge = 1;
21: }
22:
23: SimpleCat::~SimpleCat()
24: {

238 Day 8

Free download pdf