Expert C Programming

(Jeff_L) #1

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.


Programming Challenge


Do Something Destructive


Write a body for the Fruit destructor including a printf() statement, and declare a
Fruit object in an inner scope. You will need to #include <stdio.h> at the start of
your program. Then recompile and run the a.out file, checking that the destructor is called
when the object goes out of scope.


Inheritance—Reusing Operations that Are Already Defined

Single inheritance occurs when a class specializes, or refines, the data structures and methods of a
single base class. That creates a hierarchy, similar to a scientific taxonomy. Each level is a
specialization of the one above. Type inheritance is an essential part of OOP, and it is a concept that
doesn't really exist in C. Get ready to spring forward with that "conceptual leap"!


Software Dogma

Free download pdf