tailieunhanh - A Complete Guide to Programming in C++ part 49

A Complete Guide to Programming in C++ part 49. This book provides both novice and experienced programmers with a comprehensive resource manual for the C++ programming language. Readers gain experience in all aspects of programming, from elementary language concepts to professional software development, with in depth coverage of all the language elements en route. These elements are carefully ordered to help the reader create useful programs every step of the way. | DYNAMIC STORAGE ALLOCATION FOR CLASSES 459 The operators new and delete were designed to create and destroy instances of a class dynamically. In this case in addition to allocating memory a suitable constructor must be called. Before releasing memory the destructor must be called to perform cleaning up tasks. However the operators new and delete ensure that this happens. Calling new with a Default Constructor A call to new for a class is not much different from a call for a fundamental type. Unless explicitly initialized the default constructor is called for each new object but you must make sure that a default constructor exists Example Euro pEuro new Euro This statement allocates memory for an object of the Euro class. If enough memory is available the default constructor for Euro is executed and the address of a new object returned. Explicit Initialization To initialize an object explicitly you can state its initial values in parentheses when you call new. Syntax Type ptr new Type initializing_list The values in the initialization list are passed as arguments to the constructor. If the compiler is unable to locate a suitable constructor an error message occurs. Example Euro pE new Euro -12 3 77 This statement assigns the address of a new Euro class object to the pointer pE. The object is initialized using the supplied values. The expression pE thus represents the entire object. Example pE 2 00 To add 2 00 euros. The public members are referred to via the member access operator - . Example cout pE- getCents endl 33 Releasing Memory When an object that was created dynamically is destroyed the delete operator makes sure that the object is cleaned up. The destructor is first called and only then is the memory space released. As previously discussed in the section on fundamental types when you call delete you must ensure that the pointer is addressing a dynamic object or that you are dealing with a NULL pointer. 460 CHAPTER 2 1 DYNAMIC MEMORY ALLOCATION DYNAMIC .

TỪ KHÓA LIÊN QUAN