Classes Part II

Constant Objects and Const Member Functions

Constant Object

A constant object is non-modifiable, and must be initialized. For example,
	const Time noon(12, 0, 0);
Only constant member functions can call for constant objects.

Const Member Functions

Constant member functions cannot modify the object.
class TimeType
{
public:				// Public member functions
    void Set( int hours, int minutes, int seconds );

    void Increment();

    void Write() const;		// const member functions:
				        //	not to modify the private data

private:			// Private data, default 
    int hrs;
    int mins;
    int secs;
};

Example: class Time

Another Example: class datetype

Constant Data Members

Constant data members must be initialized using member initializer.

Example: class Increment

Composition: Classes As Members of Other Classes

#include "time.h"

class TimeCard
{
public:
    void Punch( int hours, int minutes, int seconds );
    void Print() const;
    TimeCard( long idNum, int initHrs, int initMins, int initSecs );
    TimeCard();

private:
    long id;
    Time timeStamp;
};

Implementation

void TimeCard::Print() const
{
    cout << "ID: " << id << " Time: ";
    timeStamp.Write();
}

void TimeCard::Punch( int hours, int minutes, int seconds )
{
    timeStamp.Set(hours, minutes, seconds);
}
							   
TimeCard::TimeCard( long idNum,	int initHrs, int initMins, int initSecs )
	:timeStamp( initHrs, initMins, initSecs )   // Constructor initiator
														// 	use member object
{
	id = idNum;
}

Note: for Constructor initiator

    With inheritance, specify the name of the base class
    With composition, specify the name of the member object	

Another Example: Employee class

Friend Functions and Friend Classes

A friend function of a class is defined outside that class's scope, but has the right to access private members of the class.

Example: class Count

More usages in Operator Overloading

Dynamic Memory Allocation

Dynamic Objects

class Date
{
public:
    void Print() const;

    void CopyFrom( Date otherDate );	// deep copy

    Date( int initMo, int initDay, int initYr, const char* msgStr  );
                                       // Constructor, shallow copy

    Date( const Date& otherDate );
                                      // Copy-constructor

    ~Date();

private:
    int   mo;
    int   day;
    int   yr;
    char* msg;
};
Notes: Complete implementation in date.cpp.

Class Destructors

Date::~Date()	// Destructor
{
    delete [] msg;
}

this Pointer

  1. the pointer point to the object itself
  2. to prevent an object from being assigned to itself
  3. to enable concatenated member function calls:

    t.setHour(18).setMinute(30).setSecond(22);

Example: Chaining of function calls

Static Class Members

Scope and Lifetime