Expert C Programming

(Jeff_L) #1

private: int weight, calories_per_oz;


} ;


void Fruit::peel(){ printf("this ptr=%p", this);


this->weight--;


weight--;}


Fruit apple;


printf("address of apple=%x",&apple);


apple.peel();


Programming Challenge


Call the Methods



  1. Make calls to the methods slice() and juice() that you wrote in the
    previous exercise.

  2. Experiment with accessing the this pointer that is the implicitly-passed first
    argument to every method.


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

Free download pdf