fb

Ads

Pages

Constructors and Destructors

Most classes have at least one constructor. This is a function that is implicitly called whenever an object of that class is created. It sets initial values in the objects. There is also a corresponding clean-up function, called a "destructor," which is invoked when an object is destroyed (goes out of scope or is
returned to the heap). Destructors are less common than constructors, and you write the code to handle any special termination needs, garbage collection, and so on. Some people use destructors as a bulletproof way to ensure that synchronization locks are always released on exit from appropriate
scopes. So they not only clean up an object, but also the locks that the object held. Constructors and destructors are needed because no one outside the class is able to access the private data. Therefore, you need a privileged function inside the class to create an object and fill in its initial data values.
This is a bit of a leap from C, where you just initialize a variable with an assignment in its definition, or even leave it uninitialized. You can define several different constructor functions, and tell them apart by their arguments. Constructor functions always have the same name as the class, and look like
this:
Classname :: Classname (arguments) { . . . };
 

In the fruit example:
 

class Fruit { public: peel(); slice(); juice();
Fruit(int i, int j); // constructor
~Fruit(); // destructor
private: int weight, calories_per_oz;
} ;
// constructor body
Fruit::Fruit(int i, int j) { weight=i; calories_per_oz=j; }
// object declarations are initialized by the constructor.
Fruit melon(4,5), banana(12,8);



Constructors are needed because classes typically contain structs with many fields, requiring sophisticated initialization. An object's constructor function will be called automatically whenever an object of that class is created, and should never be invoked explicitly by the programmer. For a global,
static object, its constructor will be automatically called at program start-up, and its destructor will be called at program exit.
Constructors and destructors violate the "nothing up my sleeve" approach of C. They cause potentially large amounts of work to be done implicitly at runtime on the programmer's behalf, breaking the C philosophy that nothing in the language should require implementation by a hidden runtime routine.

0 comments:

Post a Comment