// Phones1.cpp - Example of simple inheritance without polymorphism.
// From an idea of Coplein's "Advanced C++ Styles and Idioms", 1992,
// page 93. Note many details have been omitted for the sake of clarity.
//
// Written by Wayne Pollock, Tampa Florida USA, 2000.
enum PhoneType ( POTS, ISDN, OPERATOR, PRINCESS, OTHER );
class Telephone
{
public:
PhoneType phone_type () const { return phone_type_val; }
void ring ();
bool isOnHook ();
bool isTalking ();
bool isDialing ();
LineNumber get_extension ();
~Telephone ();
protected:
Telephone (); // Trick so only derived classes can invoke the constructor.
// (A poor-man's abstract class; there is a better way!)
LineNumber extension;
Phonetype phone_type_val;
};
class POTSPhone : public Telephone // POTS = Plain Old Telephone Service
{
public:
POTSPhone () : phone_type_val(POTS) { ... }
POTSPhone ( const POTSPhone & );
~POTSPhone ();
...
private:
Frame frame_number; // these members relate to details of a phone's
Rack rack_number; // wiring, location, and connections.
Pair pair_number;
};
class ISDNPhone : public Telephone // Integrated Services digital Network
{
public:
ISDNPhone () : phone_type_val(ISDN) { ... }
ISDNPhone ( const ISDNPhone & ) : phone_type_val(ISDN);
~ISDNPhone ();
void sendBPacket ();
void sendDPacket ();
private:
Channel b1, b2, d; // Standard residential ISDN has 3 channels.
};
class OperatorPhone : public ISDNPhone // Note: inherits from ISDNPhone.
{
public:
OperatorPhone () : phone_val_type(OPERATOR) { ... }
OperatorPhone ( const OperatorPhone & ) : phone_type_val(OPERATOR) { ... }
~OperatorPhone ();
void ring (); // Special ringing needed for operator.
...
};
class PrincessPhone : public POTSPhone // A kind of POTSPhone.
{ ... };
void ring_phones ( Telephone* phone_list [] )
{
for ( Telephone* p = phone_list; p; ++p ) // End of list marked with NULL
// Using p->ring() would invoke Telephone::ring()
switch ( p->phone_type() )
{
case POTS: ( (POTSPhone *) p )->ring(); break;
case ISDN: ( (ISDNPhone *) p )->ring(); break;
case Operator: ( (OperatorPhone *) p )->ring(); break;
...
default: error( "unknown Phone Type!" );
}
}
int main ()
{
Telephone* phone_array[10];
int i = 0;
phone_array[i++] = new POTSPhone( "5384" );
phone_array[i++] = new ISDNPhone( "1050" );
phone_array[i++] = new OperatorPhone( "0" );
phone_array[i++] = new POTSPhone( "5385" );
...
phone_array[i++] = NULL;
ring_phones( phone_array );
...
delete_phones( phone_array ); // This function is similar to ring_phones().
return 0;
}
|