the standard inheritance sample
Some program sources from "How to C++ program". And I edited some sources. I wanna demonstrate how to make a type casting between base class and derived class.(Certainly, we must type_cast derived class to base class.). I will recount more details later.
--------------------------------------------
employee1.cpp
--------------------------------------------
#include
#include
#include
#include
using namespace std;
class Employee {
public:
Employee( const char *, const char * );
~Employee();
const char *getFirstName() const;
const char *getLastName() const;
void print() const;
private:
char *firstName;
char *lastName;
};
Employee::Employee( const char *first, const char *last )
{
firstName = new char[ strlen( first ) + 1 ];
assert( firstName != 0 );
strcpy( firstName, first );
lastName = new char [ strlen( last ) + 1 ];
assert( lastName != 0 );
strcpy( lastName, last );
}
Employee::~Employee()
{
delete [] firstName;
delete [] lastName;
}
const char *Employee::getFirstName() const
{ return firstName; }
const char *Employee::getLastName() const
{ return lastName; }
void Employee::print() const
{
cout << lastName << ' ' << firstName;
}
class HourlyWorker : public Employee {
public:
HourlyWorker( const char *, const char *, double = 0.00, double = 0.00);
double getPay() const;
void print() const;
private:
double wage;
double hours;
};
HourlyWorker::HourlyWorker( const char *first,
const char *last,
double initHours, double initWage )
: Employee( first, last )
{
hours = initHours;
wage = initWage;
}
double HourlyWorker::getPay() const
{ return hours * wage; }
void HourlyWorker::print() const
{
cout << "HourlyWorker::print() is executing\n";
Employee::print();
cout << " is an hourly worker with pay of $"
<< setiosflags( ios::fixed | ios::showpoint )
<< setprecision( 2 ) << getPay() << endl;
}
int main()
{
HourlyWorker h( "Fantasy", "Final", 12.00, 43.00 );
h.print();
/* Demonstrating how to make base class type casting to derived class */
Employee *ePtr = 0, e( "Ken", "Stephen" );
HourlyWorker *hwPtr = 0, hw( "Job", "Steve", 31.00, 22.00 );
ePtr = &e;
cout << "\n\nePtr->print(), ePtr = &e:\n";
ePtr->print();
hwPtr = static_cast<> ( ePtr );
cout << "\n\nhwPtr->print(), before point to hw:\n";
hwPtr->print();
hwPtr = &hw;
cout << "\n\nhwPtr->print(), after point to hw:\n";
hwPtr->print();
cout << "\n\n";
return 0;
}
--------------------------------------------
output
--------------------------------------------
mathsniper:~# ./employee1
HourlyWorker::print() is executing
Final Fantasy is an hourly worker with pay of $516.00
ePtr->print(), ePtr = &e:
Stephen Ken
hwPtr->print(), before point to hw:
HourlyWorker::print() is executing
Stephen Ken is an hourly worker with pay of $0.00
hwPtr->print(), after point to hw:
HourlyWorker::print() is executing
Steve Job is an hourly worker with pay of $682.00
0 Comments:
Post a Comment
<< Home