Member Data on the Heap

One or more of the data members of a class can be a pointer to an object on the heap. The memory can be allocated in the class constructor or in one of its methods, and it can be deleted in its destructor, as Listing 10.3 illustrates.

Listing 10.3. Pointers as Data Members
 0: // Listing 10.3 1: // Pointers as data members 2: #include <iostream> 3: 4: class SimpleCat 5: { 6: public: 7: SimpleCat(); 8: ~SimpleCat(); 9: int GetAge() const { return *itsAge; } 10: void SetAge(int age) { *itsAge = age; } 11: 12: int GetWeight() const { return *itsWeight; } 13: void setWeight (int weight) { *itsWeight = weight; } 14: 15: private: 16: int * itsAge; 17: int * itsWeight; 18: }; 19: 20: SimpleCat::SimpleCat() 21: { 22: itsAge ...

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.