O'Reilly logo

Sams Teach Yourself C++ in 24 Hours, Third Edition by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required