Constructors and Destructors

An object will often need to be put into some initial state. The set() method does this for Point objects, as does make(). This does fine for simple classes like Point, but more complex classes need to set themselves up properly for business. You cannot safely use such an object without initializing it, and it is easy to forget to explicitly initialize an object. Constructors are special methods that will automatically be called when an object is declared.

Objects often allocate memory dynamically and, therefore, require destruction as well as construction: Any pointer allocated with new must be given back to the system with delete, etc. Destructors are methods that will be called when the life of an object is over. ...

Get C++ By Example: UnderC Learning 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.