Solutions for H7. Lecture: Xu Ying Liu
|
|
- Elwin Houston
- 6 years ago
- Views:
Transcription
1 Lecture: Xu Ying Liu Ex // Exercise Solution: Date.h 2 // Date class definition. 3 #ifndef DATE_H 4 #define DATE_H 6 #include <iostream> 7 using namespace std; 8 9 class Date 10 { 11 friend ostream &operator<<( ostream &, const Date & ); 12 public: 13 Date( int m = 1, int d = 1, int y = 1900 ); // default constructor 14 void setdate( int, int, int ); // set month, day, year 1 Date &operator++(); // prefix increment operator 16 Date operator++( int ); // postfix increment operator 17 const Date &operator+=( int ); // add days, modify object 18 bool leapyear( int ) const; // is date in a leap year? 19 bool endofmonth( int ) const; // is date at the end of month? 20 int getmonth() const; // return the month of the date 21 private: 22 int month; 23 int day; 24 int year; 2 26 static const int days[]; // array of days per month 27 void helpincrement(); // utility function for incrementing date 28 }; // end class Date #endif 1 // Exercise Solution: Date.cpp 2 // Date class member-function definitions. 3 #include <iostream> 4 #include "Date.h"
2 6 // initialize static member at file scope; one classwide copy 7 const int Date::days[] = 8 { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; 9 10 // Date constructor 11 Date::Date( int m, int d, int y ) 12 { 13 setdate( m, d, y ); 14 } // end Date constructor 1 16 // set month, day and year 17 void Date::setDate( int mm, int dd, int yy ) 18 { 19 month = ( mm >= 1 && mm <= 12 )? mm : 1; 20 year = ( yy >= 1900 && yy <= 2100 )? yy : 1900; // test for a leap year 23 if ( month == 2 && leapyear( year ) ) 24 day = ( dd >= 1 && dd <= 29 )? dd : 1; 2 else 26 day = ( dd >= 1 && dd <= days[ month ] )? dd : 1; 27 } // end function setdate // overloaded prefix increment operator 30 Date &Date::operator++() 31 { 32 helpincrement(); // increment date 33 return *this; // reference return to create an lvalue 34 } // end function operator // overloaded postfix increment operator; note that the 37 // dummy integer parameter does not have a parameter name 38 Date Date::operator++( int ) 39 { 40 Date temp = *this; // hold current state of object 41 helpincrement(); // return unincremented, saved, temporary object 44 return temp; // value return; not a reference return 4 } // end function operator // add specified number of days to date 48 const Date &Date::operator+=( int additionaldays ) 49 { 0 for ( int i = 0; i < additionaldays; i++ ) 2
3 1 helpincrement(); 2 3 return *this; // enables cascading 4 } // end function operator+= 6 // if the year is a leap year, return true; otherwise, return false 7 bool Date::leapYear( int testyear ) const 8 { 9 if ( testyear % 400 == 0 60 ( testyear % 100!= 0 && testyear % 4 == 0 ) ) 61 return true; // a leap year 62 else 63 return false; // not a leap year 64 } // end function leapyear 6 66 // return the month of the date 67 int Date::getMonth() const 68 { 69 return month; 70 } // end function getmonth // determine whether the day is the last day of the month 73 bool Date::endOfMonth( int testday ) const 74 { 7 if ( month == 2 && leapyear( year ) ) 76 return testday == 29; // last day of Feb. in leap year 77 else 78 return testday == days[ month ]; 79 } // end function endofmonth // function to help increment the date 82 void Date::helpIncrement() 83 { 84 // day is not end of month 8 if (!endofmonth( day ) ) 86 day++; // increment day 87 else 88 if ( month < 12 ) // day is end of month and month < { 90 month++; // increment month 91 day = 1; // first day of new month 92 } // end if 93 else // last day of year 94 { 9 year++; // increment year 96 month = 1; // first month of new year 3
4 97 day = 1; // first day of new month 98 } // end else 99 } // end function helpincrement // overloaded output operator 102 ostream &operator<<( ostream &output, const Date &d ) 103 { 104 static char *monthname[ 13 ] = { "", "January", "February", 10 "March", "April", "May", "June", "July", "August", 106 "September", "October", "November", "December" }; 107 output << monthname[ d.month ] << ' ' << d.day << ", " << d.year; 108 return output; // enables cascading 109 } // end function operator<< 1 // Exercise Solution: Employee.h 2 // Employee abstract base class. 3 #ifndef EMPLOYEE_H 4 #define EMPLOYEE_H 6 #include <string> // C++ standard string class 7 #include "Date.h" // Date class definition 8 using namespace std; 9 10 class Employee 11 { 12 public: 13 Employee( const string &, const string &, const string &, 14 int, int, int ); 1 16 void setfirstname( const string & ); // set first name 17 string getfirstname() const; // return first name void setlastname( const string & ); // set last name 20 string getlastname() const; // return last name void setsocialsecuritynumber( const string & ); // set SSN 23 string getsocialsecuritynumber() const; // return SSN 24 2 void setbirthdate( int, int, int ); // set birthday 26 Date getbirthdate() const; // return birthday // pure virtual function makes Employee abstract base class 29 virtual double earnings() const = 0; // pure virtual 30 virtual void print() const; // virtual 31 private: 4
5 32 string firstname; 33 string lastname; 34 string socialsecuritynumber; 3 Date birthdate; // the Employee's birthday 36 }; // end class Employee #endif // EMPLOYEE_H 1 // Exercise Solution: Employee.cpp 2 // Abstract-base-class Employee member-function definitions. 3 // Note: No definitions are given for pure virtual functions. 4 #include <iostream> #include "Employee.h" // Employee class definition 6 using namespace std; 7 8 // constructor 9 Employee::Employee( const string &first, const string &last, 10 const string &ssn, int month, int day, int year ) 11 : firstname( first ), lastname( last ), socialsecuritynumber( ssn ), 12 birthdate( month, day, year ) 13 { 14 // empty body 1 } // end Employee constructor // set first name 18 void Employee::setFirstName( const string &first ) 19 { 20 firstname = first; 21 } // end function setfirstname // return first name 24 string Employee::getFirstName() const 2 { 26 return firstname; 27 } // end function getfirstname // set last name 30 void Employee::setLastName( const string &last ) 31 { 32 lastname = last; 33 } // end function setlastname 34 3 // return last name 36 string Employee::getLastName() const 37 {
6 38 return lastname; 39 } // end function getlastname // set social security number 42 void Employee::setSocialSecurityNumber( const string &ssn ) 43 { 44 socialsecuritynumber = ssn; // should validate 4 } // end function setsocialsecuritynumber // return social security number 48 string Employee::getSocialSecurityNumber() const 49 { 0 return socialsecuritynumber; 1 } // end function getsocialsecuritynumber 2 3 // set birthday 4 void Employee::setBirthDate( int month, int day, int year ) { 6 birthdate.setdate( month, day, year ); 7 } // end function setbirthdate 8 9 // return birthday 60 Date Employee::getBirthDate() const 61 { 62 return birthdate; 63 } // end function getbirthdate 64 6 // print Employee's information (virtual, but not pure virtual) 66 void Employee::print() const 67 { 68 cout << getfirstname() << ' ' << getlastname() 69 << "\nbirthday: " << getbirthdate() 70 << "\nsocial security number: " << getsocialsecuritynumber(); 71 } // end function print 1 // Exercise Solution: HourlyEmployee.h 2 // HourlyEmployee class definition. 3 #ifndef HOURLY_H 4 #define HOURLY_H 6 #include "Employee.h" // Employee class definition 7 8 class HourlyEmployee : public Employee 9 { 10 public: 6
7 11 static const int hoursperweek = 168; // hours in one week HourlyEmployee( const string &, const string &, 14 const string &, int, int, int, double = 0.0, double = 0.0 ); 1 16 void setwage( double ); // set hourly wage 17 double getwage() const; // return hourly wage void sethours( double ); // set hours worked 20 double gethours() const; // return hours worked // keyword virtual signals intent to override 23 virtual double earnings() const; // calculate earnings 24 virtual void print() const; // print HourlyEmployee object 2 private: 26 double wage; // wage per hour 27 double hours; // hours worked for week 28 }; // end class HourlyEmployee #endif // HOURLY_H 1 // Exercise Solution: HourlyEmployee.cpp 2 // HourlyEmployee class member-function definitions. 3 #include <iostream> 4 #include "HourlyEmployee.h" // HourlyEmployee class definition using namespace std; 6 7 // constructor 8 HourlyEmployee::HourlyEmployee( const string &first, const string &last, 9 const string &ssn, int month, int day, int year, 10 double hourlywage, double hoursworked ) 11 : Employee( first, last, ssn, month, day, year ) 12 { 13 setwage( hourlywage ); // validate hourly wage 14 sethours( hoursworked ); // validate hours worked 1 } // end HourlyEmployee constructor // set wage 18 void HourlyEmployee::setWage( double hourlywage ) 19 { 20 wage = ( hourlywage < 0.0? 0.0 : hourlywage ); 21 } // end function setwage // return wage 24 double HourlyEmployee::getWage() const 7
8 2 { 26 return wage; 27 } // end function getwage // set hours worked 30 void HourlyEmployee::setHours( double hoursworked ) 31 { 32 hours = ( ( ( hoursworked >= 0.0 ) && 33 ( hoursworked <= hoursperweek ) )? hoursworked : 0.0 ); 34 } // end function sethours 3 36 // return hours worked 37 double HourlyEmployee::getHours() const 38 { 39 return hours; 40 } // end function gethours // calculate earnings; 43 // override pure virtual function earnings in Employee 44 double HourlyEmployee::earnings() const 4 { 46 if ( gethours() <= 40 ) // no overtime 47 return getwage() * gethours(); 48 else 49 return 40 * getwage() + ( ( gethours() - 40 ) * getwage() * 1. ); 0 } // end function earnings 1 2 // print HourlyEmployee's information 3 void HourlyEmployee::print() const 4 { cout << "hourly employee: "; 6 Employee::print(); // code reuse 7 cout << "\nhourly wage: " << getwage() << 8 "; hours worked: " << gethours(); 9 } // end function print 1 // Exercise Solution: SalariedEmployee.h 2 // SalariedEmployee class derived from Employee. 3 #ifndef SALARIED_H 4 #define SALARIED_H 6 #include "Employee.h" // Employee class definition 7 8 class SalariedEmployee : public Employee 9 { 8
9 10 public: 11 SalariedEmployee( const string &, const string &, 12 const string &, int, int, int, double = 0.0 ); void setweeklysalary( double ); // set weekly salary 1 double getweeklysalary() const; // return weekly salary // keyword virtual signals intent to override 18 virtual double earnings() const; // calculate earnings 19 virtual void print() const; // print SalariedEmployee object 20 private: 21 double weeklysalary; // salary per week 22 }; // end class SalariedEmployee #endif // SALARIED_H 1 // Exercise Solution: SalariedEmployee.cpp 2 // SalariedEmployee class member-function definitions. 3 #include <iostream> 4 #include "SalariedEmployee.h" // SalariedEmployee class definition using namespace std; 6 7 // constructor 8 SalariedEmployee::SalariedEmployee( const string &first, 9 const string &last, const string &ssn, int month, int day, int year, 10 double salary ) 11 : Employee( first, last, ssn, month, day, year ) 12 { 13 setweeklysalary( salary ); 14 } // end SalariedEmployee constructor 1 16 // set salary 17 void SalariedEmployee::setWeeklySalary( double salary ) 18 { 19 weeklysalary = ( salary < 0.0 )? 0.0 : salary; 20 } // end function setweeklysalary // return salary 23 double SalariedEmployee::getWeeklySalary() const 24 { 2 return weeklysalary; 26 } // end function getweeklysalary // calculate earnings; 29 // override pure virtual function earnings in Employee 9
10 30 double SalariedEmployee::earnings() const 31 { 32 return getweeklysalary(); 33 } // end function earnings 34 3 // print SalariedEmployee's information 36 void SalariedEmployee::print() const 37 { 38 cout << "salaried employee: "; 39 Employee::print(); // reuse abstract base-class print function 40 cout << "\nweekly salary: " << getweeklysalary(); 41 } // end function print 1 // Exercise Solution: CommissionEmployee.h 2 // CommissionEmployee class derived from Employee. 3 #ifndef COMMISSION_H 4 #define COMMISSION_H 6 #include "Employee.h" // Employee class definition 7 8 class CommissionEmployee : public Employee 9 { 10 public: 11 CommissionEmployee( const string &, const string &, 12 const string &, int, int, int, double = 0.0, double = 0.0 ); void setcommissionrate( double ); // set commission rate 1 double getcommissionrate() const; // return commission rate void setgrosssales( double ); // set gross sales amount 18 double getgrosssales() const; // return gross sales amount // keyword virtual signals intent to override 21 virtual double earnings() const; // calculate earnings 22 virtual void print() const; // print CommissionEmployee object 23 private: 24 double grosssales; // gross weekly sales 2 double commissionrate; // commission percentage 26 }; // end class CommissionEmployee #endif // COMMISSION_H 1 // Exercise Solution: CommissionEmployee.cpp 2 // CommissionEmployee class member-function definitions. 10
11 3 #include <iostream> 4 #include "CommissionEmployee.h" // CommissionEmployee class definition using namespace std; 6 7 // constructor 8 CommissionEmployee::CommissionEmployee( const string &first, 9 const string &last, const string &ssn, int month, int day, int year, 10 double sales, double rate ) 11 : Employee( first, last, ssn, month, day, year ) 12 { 13 setgrosssales( sales ); 14 setcommissionrate( rate ); 1 } // end CommissionEmployee constructor // set commission rate 18 void CommissionEmployee::setCommissionRate( double rate ) 19 { 20 commissionrate = ( ( rate > 0.0 && rate < 1.0 )? rate : 0.0 ); 21 } // end function setcommissionrate // return commission rate 24 double CommissionEmployee::getCommissionRate() const 2 { 26 return commissionrate; 27 } // end function getcommissionrate // set gross sales amount 30 void CommissionEmployee::setGrossSales( double sales ) 31 { 32 grosssales = ( ( sales < 0.0 )? 0.0 : sales ); 33 } // end function setgrosssales 34 3 // return gross sales amount 36 double CommissionEmployee::getGrossSales() const 37 { 38 return grosssales; 39 } // end function getgrosssales // calculate earnings; 42 // override pure virtual function earnings in Employee 43 double CommissionEmployee::earnings() const 44 { 4 return getcommissionrate() * getgrosssales(); 46 } // end function earnings // print CommissionEmployee's information 11
12 49 void CommissionEmployee::print() const 0 { 1 cout << "commission employee: "; 2 Employee::print(); // code reuse 3 cout << "\ngross sales: " << getgrosssales() 4 << "; commission rate: " << getcommissionrate(); } // end function print 1 // Exercise Solution: BasePlusCommissionEmployee.h 2 // BasePlusCommissionEmployee class derived from CommissionEmployee. 3 #ifndef BASEPLUS_H 4 #define BASEPLUS_H 6 #include "CommissionEmployee.h" // CommissionEmployee class definition 7 8 class BasePlusCommissionEmployee : public CommissionEmployee 9 { 10 public: 11 BasePlusCommissionEmployee( const string &, const string &, 12 const string &, int, int, int, double = 0.0, double = 0.0, 13 double = 0.0 ); 14 1 void setbasesalary( double ); // set base salary 16 double getbasesalary() const; // return base salary // keyword virtual signals intent to override 19 virtual double earnings() const; // calculate earnings 20 virtual void print() const; // print BasePlusCommissionEmployee object 21 private: 22 double basesalary; // base salary per week 23 }; // end class BasePlusCommissionEmployee 24 2 #endif // BASEPLUS_H 1 // Exercise Solution: BasePlusCommissionEmployee.cpp 2 // BasePlusCommissionEmployee member-function definitions. 3 #include <iostream> 4 // BasePlusCommissionEmployee class definition 6 #include "BasePlusCommissionEmployee.h" 7 using namespace std; 8 9 // constructor 10 BasePlusCommissionEmployee::BasePlusCommissionEmployee( 12
13 11 const string &first, const string &last, const string &ssn, 12 int month, int day, int year, double sales, 13 double rate, double salary ) 14 : CommissionEmployee( first, last, ssn, month, day, year, sales, rate ) 1 { 16 setbasesalary( salary ); // validate and store base salary 17 } // end BasePlusCommissionEmployee constructor // set base salary 20 void BasePlusCommissionEmployee::setBaseSalary( double salary ) 21 { 22 basesalary = ( ( salary < 0.0 )? 0.0 : salary ); 23 } // end function setbasesalary 24 2 // return base salary 26 double BasePlusCommissionEmployee::getBaseSalary() const 27 { 28 return basesalary; 29 } // end function getbasesalary // calculate earnings; 32 // override pure virtual function earnings in Employee 33 double BasePlusCommissionEmployee::earnings() const 34 { 3 return getbasesalary() + CommissionEmployee::earnings(); 36 } // end function earnings // print BasePlusCommissionEmployee's information 39 void BasePlusCommissionEmployee::print() const 40 { 41 cout << "base-salaried "; 42 CommissionEmployee::print(); // code reuse 43 cout << "; base salary: " << getbasesalary(); 44 } // end function print 1 // Exercise Solution: ex13_12.cpp 2 // Processing Employee derived-class objects polymorphically. 3 #include <iostream> 4 #include <iomanip> #include <vector> 6 #include <typeinfo> 7 #include <ctime> 8 9 // include definitions of classes in Employee hierarchy 10 #include "Employee.h" 13
14 11 #include "SalariedEmployee.h" 12 #include "HourlyEmployee.h" 13 #include "CommissionEmployee.h" 14 #include "BasePlusCommissionEmployee.h" 1 using namespace std; int determinemonth(); // prototype of function that returns current month int main() 20 { 21 // set floating-point output formatting 22 cout << fixed << setprecision( 2 ); // create vector of four base-class pointers 2 vector < Employee * > employees( 4 ); // initialize vector with Employees 28 employees[ 0 ] = new SalariedEmployee( 29 "John", "Smith", " ", 6, 1, 1944, 800 ); 30 employees[ 1 ] = new HourlyEmployee( 31 "Karen", "Price", " ", 12, 29, 1960, 16.7, 40 ); 32 employees[ 2 ] = new CommissionEmployee( 33 "Sue", "Jones", " ", 9, 8, 194, 10000,.06 ); 34 employees[ 3 ] = new BasePlusCommissionEmployee( 3 "Bob", "Lewis", " ", 3, 2, 196, 000,.04, 300 ); int month = determinemonth(); cout << "Employees processed polymorphically via dynamic binding:\n\n"; for ( size_t i = 0; i < employees.size(); i++ ) 42 { 43 employees[ i ]->print(); // output employee information 44 cout << endl; 4 46 // downcast pointer 47 BasePlusCommissionEmployee *derivedptr = 48 dynamic_cast < BasePlusCommissionEmployee * > 49 ( employees[ i ] ); 0 1 // determine whether element points to base-salaried 2 // commission employee 3 if ( derivedptr!= 0 ) // 0 if not a BasePlusCommissionEmployee 4 { double oldbasesalary = derivedptr->getbasesalary(); 6 cout << "old base salary: $" << oldbasesalary << endl; 14
15 7 derivedptr->setbasesalary( 1.10 * oldbasesalary ); 8 cout << "new base salary with 10% increase is: $" 9 << derivedptr->getbasesalary() << endl; 60 } // end if // get current employee's birthday 63 Date birthday = employees[ i ]->getbirthdate(); 64 6 // if current month is employee's birthday month, add $100 to salary 66 if ( birthday.getmonth() == month ) 67 cout << "HAPPY BIRTHDAY!\nearned $" 68 << ( employees[ i ]->earnings() ) << endl; 69 else 70 cout << "earned $" << employees[ i ]->earnings() << endl; cout << endl; 73 } // end for 74 7 // release objects pointed to by vector 抯 '92selements 76 for ( size_t j = 0; j < employees.size(); j++ ) 77 { 78 // output class name 79 cout << "deleting object of " 80 << typeid( *employees[ j ] ).name() << endl; delete employees[ j ]; 83 } // end for 84 } // end main 8 86 // Determine the current month using standard library functions of ctime 87 int determinemonth() 88 { 89 time_t currenttime; 90 char monthstring[ 3 ]; 91 time( ¤ttime ); 92 strftime( monthstring, 3, "%m", localtime( ¤ttime ) ); 93 return atoi( monthstring ); 94 } // end function determinemonth 1
16 Ex // Solution Solution: Account.h 2 // Definition of Account class. 3 #ifndef ACCOUNT_H 4 #define ACCOUNT_H 6 class Account 7 { 8 public: 9 Account( double ); // constructor initializes balance 10 virtual void credit( double ); // add an amount to the account balance 11 virtual bool debit( double ); // subtract an amount from the balance 12 void setbalance( double ); // sets the account balance 13 double getbalance(); // return the account balance 14 private: 1 double balance; // data member that stores the balance 16 }; // end class Account #endif 1 // Exercise Solution: Account.cpp 2 // Member-function definitions for class Account. 3 #include <iostream> 4 #include "Account.h" // include definition of class Account using namespace std; 6 7 // Account constructor initializes data member balance 8 Account::Account( double initialbalance ) 9 { 10 // if initialbalance is greater than or equal to 0.0, set this value 11 // as the balance of the Account 12 if ( initialbalance >= 0.0 ) 13 balance = initialbalance; 14 else // otherwise, output message and set balance to { 16 cout << "Error: Initial balance cannot be negative." << endl; 17 balance = 0.0; 18 } // end if...else 19 } // end Account constructor // credit (add) an amount to the account balance 22 void Account::credit( double amount ) 23 { 24 balance = balance + amount; // add amount to balance 2 } // end function credit 16
17 26 27 // debit (subtract) an amount from the account balance 28 // return bool indicating whether money was debited 29 bool Account::debit( double amount ) 30 { 31 if ( amount > balance ) // debit amount exceeds balance 32 { 33 cout << "Debit amount exceeded account balance." << endl; 34 return false; 3 } // end if 36 else // debit amount does not exceed balance 37 { 38 balance = balance - amount; 39 return true; 40 } // end else 41 } // end function debit // set the account balance 44 void Account::setBalance( double newbalance ) 4 { 46 balance = newbalance; 47 } // end function setbalance // return the account balance 0 double Account::getBalance() 1 { 2 return balance; 3 } // end function getbalance 1 // Exercise Solution: CheckingAccount.h 2 // Definition of CheckingAccount class. 3 #ifndef CHECKING_H 4 #define CHECKING_H 6 #include "Account.h" // Account class definition 7 8 class CheckingAccount : public Account 9 { 10 public: 11 // constructor initializes balance and transaction fee 12 CheckingAccount( double, double ); virtual void credit( double ); // redefined credit function 1 virtual bool debit( double ); // redefined debit function 16 private: 17
18 17 double transactionfee; // fee charged per transaction // utility function to charge fee 20 void chargefee(); 21 }; // end class CheckingAccount #endif 1 // Exercise Solution: CheckingAccount.cpp 2 // Member-function definitions for class CheckingAccount. 3 #include <iostream> 4 #include "CheckingAccount.h" // CheckingAccount class definition using namespace std; 6 7 // constructor initializes balance and transaction fee 8 CheckingAccount::CheckingAccount( double initialbalance, double fee ) 9 : Account( initialbalance ) // initialize base class 10 { 11 transactionfee = ( fee < 0.0 )? 0.0 : fee; // set transaction fee 12 } // end CheckingAccount constructor // credit (add) an amount to the account balance and charge fee 1 void CheckingAccount::credit( double amount ) 16 { 17 Account::credit( amount ); // always succeeds 18 chargefee(); 19 } // end function credit // debit (subtract) an amount from the account balance and charge fee 22 bool CheckingAccount::debit( double amount ) 23 { 24 bool success = Account::debit( amount ); // attempt to debit 2 26 if ( success ) // if money was debited, charge fee and return true 27 { 28 chargefee(); 29 return true; 30 } // end if 31 else // otherwise, do not charge fee and return false 32 return false; 33 } // end function debit 34 3 // subtract transaction fee 36 void CheckingAccount::chargeFee() 37 { 18
19 38 Account::setBalance( getbalance() - transactionfee ); 39 cout << "$" << transactionfee << " transaction fee charged." << endl; 40 } // end function chargefee 1 // Exercise Solution: SavingsAccount.h 2 // Definition of SavingsAccount class. 3 #ifndef SAVINGS_H 4 #define SAVINGS_H 6 #include "Account.h" // Account class definition 7 8 class SavingsAccount : public Account 9 { 10 public: 11 // constructor initializes balance and interest rate 12 SavingsAccount( double, double ); double calculateinterest(); // determine interest owed 1 private: 16 double interestrate; // interest rate (percentage) earned by account 17 }; // end class SavingsAccount #endif 1 // Exercise Solution: SavingsAccount.cpp 2 // Member-function definitions for class SavingsAccount. 3 4 #include "SavingsAccount.h" // SavingsAccount class definition 6 // constructor initializes balance and interest rate 7 SavingsAccount::SavingsAccount( double initialbalance, double rate ) 8 : Account( initialbalance ) // initialize base class 9 { 10 interestrate = ( rate < 0.0 )? 0.0 : rate; // set interestrate 11 } // end SavingsAccount constructor // return the amount of interest earned 14 double SavingsAccount::calculateInterest() 1 { 16 return getbalance() * interestrate; 17 } // end function calculateinterest 1 // Exercise Solution: ex13_16.cpp 19
20 2 // Processing Accounts polymorphically. 3 #include <iostream> 4 #include <iomanip> #include <vector> 6 #include "Account.h" // Account class definition 7 #include "SavingsAccount.h" // SavingsAccount class definition 8 #include "CheckingAccount.h" // CheckingAccount class definition 9 using namespace std; int main() 12 { 13 // create vector accounts 14 vector < Account * > accounts( 4 ); 1 16 // initialize vector with Accounts 17 accounts[ 0 ] = new SavingsAccount( 2.0,.03 ); 18 accounts[ 1 ] = new CheckingAccount( 80.0, 1.0 ); 19 accounts[ 2 ] = new SavingsAccount( 200.0,.01 ); 20 accounts[ 3 ] = new CheckingAccount( 400.0,. ); cout << fixed << setprecision( 2 ); // loop through vector, prompting user for debit and credit amounts 2 for ( size_t i = 0; i < accounts.size(); i++ ) 26 { 27 cout << "Account " << i + 1 << " balance: $" 28 << accounts[ i ]->getbalance(); double withdrawalamount = 0.0; 31 cout << "\nenter an amount to withdraw from Account " << i << ": "; 33 cin >> withdrawalamount; 34 accounts[ i ]->debit( withdrawalamount ); // attempt to debit 3 36 double depositamount = 0.0; 37 cout << "Enter an amount to deposit into Account " << i << ": "; 39 cin >> depositamount; 40 accounts[ i ]->credit( depositamount ); // credit amount to Account // downcast pointer 43 SavingsAccount *savingsaccountptr = 44 dynamic_cast < SavingsAccount * > ( accounts[ i ] ); 4 46 // if Account is a SavingsAccount, calculate and add interest 47 if ( savingsaccountptr!= 0 ) 20
21 48 { 49 double interestearned = savingsaccountptr->calculateinterest(); 0 cout << "Adding $" << interestearned << " interest to Account " 1 << i + 1 << " (a SavingsAccount)" << endl; 2 savingsaccountptr->credit( interestearned ); 3 } // end if 4 cout << "Updated Account " << i + 1 << " balance: $" 6 << accounts[ i ]->getbalance() << "\n\n"; 7 } // end for 8 } // end main 21
Object Oriented Programming with C++ (24)
Object Oriented Programming with C++ (24) Zhang, Xinyu Department of Computer Science and Engineering, Ewha Womans University, Seoul, Korea zhangxy@ewha.ac.kr Polymorphism (II) Chapter 13 Outline Review
More informationIS 0020 Program Design and Software Tools
1 IS 0020 Program Design and Software Tools Polymorphism Lecture 8 September 28/29, 2004 Introduction 2 Polymorphism Program in the general Derived-class object can be treated as base-class object is -a
More informationC++ Polymorphism. Systems Programming
C++ Polymorphism Systems Programming C++ Polymorphism Polymorphism Examples Relationships Among Objects in an Inheritance Hierarchy Invoking Base-Class Functions from Derived-Class Objects Aiming Derived-Class
More informationfinal Methods and Classes
1 2 OBJECTIVES In this chapter you will learn: The concept of polymorphism. To use overridden methods to effect polymorphism. To distinguish between abstract and concrete classes. To declare abstract methods
More information엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED
엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED - Polymorphism - Virtual Functions - Abstract Classes - Virtual
More informationObject-Oriented Programming: Polymorphism Pearson Education, Inc. All rights reserved.
1 10 Object-Oriented Programming: Polymorphism 2 A Motivating Example Employee as an abstract superclass. Lots of different types of employees (well, 4). Executing the same code on all different types
More informationObject-Oriented Programming: Polymorphism
Object-Oriented Programming: Polymorphism By Harvey M. Deitel and Paul J. Deitel Jun 1, 2009 Sample Chapter is provided courtesy of Prentice Hall 10.1 Introduction We now continue our study of object-oriented
More informationWEEK 13 EXAMPLES: POLYMORPHISM
WEEK 13 EXAMPLES: POLYMORPHISM CASE STUDY: PAYROLL SYSTEM USING POLYMORPHISM Use the principles of inheritance, abstract class, abstract method, and polymorphism to design a payroll project for a car lot.
More informationComputer Programming Inheritance 10 th Lecture
Computer Programming Inheritance 10 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2015 Eom, Hyeonsang All Rights Reserved 순서 Inheritance
More informationObject-Oriented Programming: Polymorphism
10 One Ring to rule them all, One Ring to find them, One Ring to bring them all and in the darkness bind them. John Ronald Reuel Tolkien General propositions do not decide concrete cases. Oliver Wendell
More informationSolutions for H6. Lecture: Xu Ying Liu
Lecture: Xu Ying Liu 2011 31 Ex12.9 1 // Exercise 12.9 Solution: Package.h 2 // Definition of base class Package. 3 #ifndef PACKAGE_H 4 #define PACKAGE_H 6 #include 7 using namespace std; 8 9
More informationOperator Overloading
Operator Overloading Introduction Operator overloading Enabling C++ s operators to work with class objects Using traditional operators with user-defined objects Requires great care; when overloading is
More informationPolymorphism. Chapter 4. CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science. Dr. S.
Chapter 4 Polymorphm CSC 113 King Saud University College Computer and Information Sciences Department Computer Science Objectives After you have read and studied th chapter, you should be able to Write
More informationIntroduction. W8.2 Operator Overloading
W8.2 Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. as friend Functions Overloading Stream Insertion and Extraction
More informationOperator Overloading
Operator Overloading Introduction Operator overloading Enabling C++ s operators to work with class objects Using traditional operators with user-defined objects Requires great care; when overloading is
More informationPolymorphism (Deitel chapter 10) (Old versions: chapter 9)
Polymorphism (Deitel chapter 10) (Old versions: chapter 9) 1 2 Plan Introduction Relationships Among Objects in an Inheritance Hierarchy Polymorphism Examples Abstract Classes and Methods Example: Inheriting
More informationW8.2 Operator Overloading
1 W8.2 Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. as friend Functions Overloading Stream Insertion and Extraction
More informationCpt S 122 Data Structures. Inheritance
Cpt S 122 Data Structures Inheritance Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Introduction Base Classes & Derived Classes Relationship between
More informationInheritance Introduction. 9.1 Introduction 361
www.thestudycampus.com Inheritance 9.1 Introduction 9.2 Superclasses and Subclasses 9.3 protected Members 9.4 Relationship Between Superclasses and Subclasses 9.4.1 Creating and Using a CommissionEmployee
More informationClasses: A Deeper Look, Part 2
10 But what, to serve our private ends, Forbids the cheating of our friends? Charles Churchill Instead of this absurd division into sexes they ought to class people as static and dynamic. Evelyn Waugh
More informationFig Fig Fig. 10.3
CHAPTER 10 VIRTUAL FUNCTIONS AND POLYMORPHISM 1 Illustrations List (Main Page) Fig. 10.2 Fig. 10.3. Definition of abstract base class Shape. Flow of control of a virtual function call. CHAPTER 10 VIRTUAL
More informationObject Oriented Design
Object Oriented Design Chapter 12 continue 12.6 Case Study: Payroll System Using Polymorphism This section reexamines the CommissionEmployee- BasePlusCommissionEmployee hierarchy that we explored throughout
More informationUsing the Xcode Debugger
g Using the Xcode Debugger J Objectives In this appendix you ll: Set breakpoints and run a program in the debugger. Use the Continue program execution command to continue execution. Use the Auto window
More informationObject- Oriented Programming: Inheritance
9 Say not you know another entirely, till you have divided an inheritance with him. Johann Kasper Lavater This method is to define as the number of a class the class of all classes similar to the given
More information6.096 Introduction to C++
MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. MASSACHUSETTS INSTITUTE
More informationClasses: A Deeper Look. Systems Programming
Classes: A Deeper Look Systems Programming Deeper into C++ Classes const objects and const member functions Composition Friendship this pointer Dynamic memory management new and delete operators static
More informationOperator overloading: extra examples
Operator overloading: extra examples CS319: Scientific Computing (with C++) Niall Madden Week 8: some extra examples, to supplement what was covered in class 1 Eg 1: Points in the (x, y)-plane Overloading
More information第三章习题答案 // include definition of class GradeBook from GradeBook.h #include "GradeBook.h"
第三章习题答案 3.11 // Exercise 3.11 Solution: GradeBook.h // Definition of GradeBook class that stores an instructor's name. #include // program uses C++ standard string class using std::string; //
More informationIntroduction to Classes and Objects
3 Introduction to Classes and Objects OBJECTIVES In this chapter you will learn: What classes, objects, methods and instance variables are. How to declare a class and use it to create an object. How to
More informationCS111: PROGRAMMING LANGUAGE II
1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 8(a): Abstract Classes Lecture Contents 2 Abstract base classes Concrete classes Dr. Amal Khalifa, 2014 Abstract Classes and Methods
More informationInheritance and Polymorphism
Inheritance and Polymorphism 1 Inheritance extending a clock to an alarm clock deriving a class 2 Polymorphism virtual functions and polymorphism abstract classes MCS 360 Lecture 8 Introduction to Data
More informationIntroduction to Classes and Objects
3 Nothing can have value without being an object of utility. Karl Marx Your public servants serve you right. Adlai E. Stevenson Knowing how to answer one who speaks, To reply to one who sends a message.
More informationHomework 3. Due: Feb 25, 23:59pm. Section 1 (20 pts, 2 pts each) Multiple Choice Questions
Homework 3 Due: Feb 25, 23:59pm Section 1 (20 pts, 2 pts each) Multiple Choice Questions Q1: A function that modifies an array by using pointer arithmetic such as ++ptr to process every value of the array
More informationBBM 102 Introduction to Programming II Spring Inheritance
BBM 102 Introduction to Programming II Spring 2018 Inheritance 1 Today Inheritance Notion of subclasses and superclasses protected members UML Class Diagrams for inheritance 2 Inheritance A form of software
More informationAssoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.
Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All Inheritance A form of software reuse in which a new class is created by absorbing an existing class s members and enriching them with
More informationFig. 7.1 Fig. 7.2 Fig. 7.3 Fig. 7.4 Fig. 7.5 Fig. 7.6 Fig. 7.7 Fig. 7.8 Fig. 7.9 Fig. 7.10
CHAPTER 7 CLASSES: PART II 1 Illustrations List (Main Page) Fig. 7.1 Fig. 7.2 Fig. 7.3 Fig. 7.4 Fig. 7.5 Fig. 7.6 Fig. 7.7 Fig. 7.8 Fig. 7.9 Fig. 7.10 Using a Time class with const objects and const member
More informationChapter 19 - C++ Inheritance
Chapter 19 - C++ Inheritance 19.1 Introduction 19.2 Inheritance: Base Classes and Derived Classes 19.3 Protected Members 19.4 Casting Base-Class Pointers to Derived-Class Pointers 19.5 Using Member Functions
More informationChapter 19 C++ Inheritance
Chapter 19 C++ Inheritance Angela Chih-Wei i Tang Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 19.11 Introduction ti 19.2 Inheritance: Base Classes
More informationInheritance. Overview. Chapter 15 & additional topics. Inheritance Introduction. Three different kinds of inheritance
Inheritance Chapter 15 & additional topics Overview Inheritance Introduction Three different kinds of inheritance Changing an inherited member function More Inheritance Details Polymorphism Motivating
More informationTutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays
Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays Outline 13.1 Test-Driving the Salary Survey Application 13.2 Introducing Arrays 13.3 Declaring and Initializing Arrays 13.4 Constructing
More informationTutorial letter 202/2/2018
COS1512/202/2/2018 Tutorial letter 202/2/2018 Introduction to Programming II COS1512 Semester 2 School of Computing This tutorial letter contains the solution to Assignment 2 IMPORTANT INFORMATION: Please
More informationAngela Chih-Wei Tang Visual Communications Lab Department of Communication Engineering National Central University JhongLi, Taiwan.
C++ Classes: Part II Angela Chih-Wei Tang Visual Communications Lab Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 17.2 const (Constant) Objects and
More informationChapter 14. Inheritance. Slide 1
Chapter 14 Inheritance Slide 1 Learning Objectives Inheritance Basics Derived classes, with constructors protected: qualifier Redefining member functions Non-inherited functions Programming with Inheritance
More informationthis Pointer, Constant Functions, Static Data Members, and Static Member Functions this Pointer (11.1) Example of this pointer
this Pointer, Constant Functions, Static Data Members, and Static Member Functions 3/2/07 CS250 Introduction to Computer Science II 1 this Pointer (11.1) functions - only one copy of each function exists
More informationInheritance. Chapter 15 & additional topics
Inheritance Chapter 15 & additional topics Overview Inheritance Introduction Three different kinds of inheritance Changing an inherited member function More Inheritance Details Polymorphism Inheritance
More informationUnit 3. C++ Language II. Takayuki Dan Kimura. Unbounded Queue. Extension of Queue Data Type. Static Members. Base and Derived Classes (Inheritance)
Unit 3 C++ Language II Object Oriented Programming in C++ Takayuki Dan Kimura Unbounded Queue Extension of Queue Data Type Static Members Base and Derived Classes (Inheritance) Virtual Functions Polymorphism
More informationObject oriented programming
Exercises 7 Version 1.0, 11 April, 2017 Table of Contents 1. Inheritance.................................................................. 1 1.1. Tennis Player...........................................................
More informationQuestion 1 Consider the following structure used to keep employee records:
Question 1 Consider the following structure used to keep employee records: struct Employee string firstname; string lastname; float salary; } Turn the employee record into a class type rather than a structure
More informationChapter 14 Inheritance. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo
Chapter 14 Inheritance 1 Learning Objectives Inheritance Basics Derived classes, with constructors Protected: qualifier Redefining member functions Non-inherited functions Programming with Inheritance
More informationCpt S 122 Data Structures. Course Review Midterm Exam # 2
Cpt S 122 Data Structures Course Review Midterm Exam # 2 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 2 When: Monday (11/05) 12:10 pm -1pm
More informationOBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++ Chapter 17 - C++ Classes: Part II 17.1 Introduction 17.2 const (Constant) Objects and const Member Functions 17.3 Composition: Objects as Members of Classes 17.4 friend
More informationComputer Programming Class Members 9 th Lecture
Computer Programming Class Members 9 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2015 Eom, Hyeonsang All Rights Reserved Outline Class
More informationPreview 11/1/2017. Constant Objects and Member Functions. Constant Objects and Member Functions. Constant Objects and Member Functions
Preview Constant Objects and Constant Functions Composition: Objects as Members of a Class Friend functions The use of Friend Functions Some objects need to be modifiable and some do not. A programmer
More informationIS 0020 Program Design and Software Tools
1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 5: Classes September 14, 2004 Structure Definitions 2 Structures Aggregate data types built using elements of other types
More informationInheritance. Chapter 15 & additional topics
Inheritance Chapter 15 & additional topics Overview Inheritance Introduction Three different kinds of inheritance Changing an inherited member function More Inheritance Details Polymorphism Inheritance
More informationChapter 17 - C++ Classes: Part II
Chapter 17 - C++ Classes: Part II 17.1 Introduction 17.2 const (Constant) Objects and const Member Functions 17.3 Composition: Objects as Members of Classes 17.4 friend Functions and friend Classes 17.5
More informationCIS 190: C/C++ Programming. Classes in C++
CIS 190: C/C++ Programming Classes in C++ Outline Header Protection Functions in C++ Procedural Programming vs OOP Classes Access Constructors Headers in C++ done same way as in C including user.h files:
More informationLecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?
CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 5: Inheritance & Polymorphism Lecture Contents 2 What is Inheritance? Super-class & sub class Protected members Creating subclasses
More informationObject Oriented Programming. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 27 December 8, What is a class? Extending a Hierarchy
CISC181 Introduction to Computer Science Dr. McCoy Lecture 27 December 8, 2009 Object Oriented Programming Classes categorize entities that occur in applications. Class teacher captures commonalities of
More informationCS313D: ADVANCED PROGRAMMING LANGUAGE
CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 5: Inheritance & Polymorphism Lecture Contents 2 What is Inheritance? Super-class & sub class Protected members Creating subclasses
More informationDo not turn to the next page until the start of the exam.
Introduction to Programming, PIC10A E. Ryu Fall 2017 Midterm Exam Friday, November 3, 2017 50 minutes, 11 questions, 100 points, 8 pages While we don t expect you will need more space than provided, you
More informationCS105 C++ Lecture 7. More on Classes, Inheritance
CS105 C++ Lecture 7 More on Classes, Inheritance " Operator Overloading Global vs Member Functions Difference: member functions already have this as an argument implicitly, global has to take another parameter.
More informationLecture 23: Pointer Arithmetic
Lecture 23: Pointer Arithmetic Wai L. Khoo Department of Computer Science City College of New York November 29, 2011 Wai L. Khoo (CS@CCNY) Lecture 23 November 29, 2011 1 / 14 Pointer Arithmetic Pointer
More information6.096 Introduction to C++
MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. MASSACHUSETTS I STITUTE
More informationIS 0020 Program Design and Software Tools
1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3: Classes May 24, 2004 2 Classes Structure Definitions 3 Structures Aggregate data types built using elements of other
More informationDue Date: See Blackboard
Source File: ~/2315/45/lab45.(C CPP cpp c++ cc cxx cp) Input: under control of main function Output: under control of main function Value: 4 Integer data is usually represented in a single word on a computer.
More informationtypedef int Array[10]; String name; Array ages;
Morteza Noferesti The C language provides a facility called typedef for creating synonyms for previously defined data type names. For example, the declaration: typedef int Length; Length a, b, len ; Length
More informationIntroduction to C++ (Extensions to C)
Introduction to C++ (Extensions to C) C is purely procedural, with no objects, classes or inheritance. C++ is a hybrid of C with OOP! The most significant extensions to C are: much stronger type checking.
More informationComputer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons
Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite
More informationYanbu University College Applied Computer Science (ACS) Introduction to Computer Science (CS 102) Lab Exercise 10
Yanbu University College BACHELOR OF SCIENCE IN Applied Computer Science (ACS) Introduction to Computer Science (CS 102) Third Semester Academic Year 2011 2012 Lab Exercise 10 Course Instructor: Mohammed
More informationCSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism
CSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism Review from Lecture 22 Added parent pointers to the TreeNode to implement increment and decrement operations on tree
More informationProgramming C++ Lecture 5. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor
Programming C++ Lecture 5 Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Templates S Function and class templates you specify with a single code segment an entire
More informationSolutions for H5. Lecture: Xu-Ying Liu
Lecture: Xu-Ying Liu 2011-5-05 Ex.11.11 1 // Exercise 11.11 Solution: DoubleSubscriptedArray.h 2 // DoubleSubscriptedArray class for storing 3 // double subscripted arrays of integers. 4 #ifndef DOUBLE_SUBSCRIPTED_ARRAY_H
More informationCSS 342 Data Structures, Algorithms, and Discrete Mathematics I. Lecture 2. Yusuf Pisan
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I Lecture 2 Yusuf Pisan Compiled helloworld yet? Overview C++ fundamentals Assignment-1 CSS Linux Cluster - submitting assignment Call by Value,
More informationIS 0020 Program Design and Software Tools
1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Operator Overloading, Inheritance Lecture 6 February 10, 2005 Fundamentals of Operator Overloading 2 Use operators with objects
More informationTutorial 8 (Array I)
Tutorial 8 (Array I) 1. Indicate true or false for the following statements. a. Every element in an array has the same type. b. The array size is fixed after it is created. c. The array size used to declare
More informationIntroduction to C++ Systems Programming
Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions
More informationCS313D: ADVANCED PROGRAMMING LANGUAGE
CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 4(b): Inheritance & Polymorphism Lecture Contents What is Inheritance? Super-class & sub class The object class Using extends keyword
More informationCOEN244: Polymorphism
COEN244: Polymorphism Aishy Amer Electrical & Computer Engineering Polymorphism means variable behavior / ability to appear in many forms Outline Casting between objects Using pointers to access objects
More informationMidterm Exam 5 April 20, 2015
Midterm Exam 5 April 20, 2015 Name: Section 1: Multiple Choice Questions (24 pts total, 3 pts each) Q1: Which of the following is not a kind of inheritance in C++? a. public. b. private. c. static. d.
More informationChapter 18 - C++ Operator Overloading
Chapter 18 - C++ Operator Overloading Outline 18.1 Introduction 18.2 Fundamentals of Operator Overloading 18.3 Restrictions on Operator Overloading 18.4 Operator Functions as Class Members vs. as friend
More informationCSCE 110 PROGRAMMING FUNDAMENTALS
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class Prof. amr Goneid, AUC 1 Dictionaries(1): A Key Table Class Prof. Amr Goneid, AUC 2 A Key Table
More informationChapter 15 - C++ As A "Better C"
Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference
More informationUniversity of Swaziland Department Of Computer Science Supplementary Examination JULY 2012
University of Swaziland Department Of Computer Science Supplementary Examination JULY 2012 Title ofpaper: Course number: Time Allowed: Cunder Unix CS344 Three (3) hours Instructions: Answer question 1.
More informationExtending Classes (contd.) (Chapter 15) Questions:
Extending Classes (contd.) (Chapter 15) Questions: 1 Virtual Functions in C++ Employee /\ / \ ---- Manager 2 Case 1: class Employee { string firstname, lastname; //... Employee( string fnam, string lnam
More informationObject Oriented Programming COP3330 / CGS5409
Object Oriented Programming COP3330 / CGS5409 Inheritance Assignment 5 Many types of classes that we create can have similarities. Useful to take advantage of the objectoriented programming technique known
More informationIS 0020 Program Design and Software Tools
1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Multiple Inheritance July 26, 2004 22.9 Multiple Inheritance 2 Multiple inheritance Derived class has several base classes Powerful,
More informationLab 2: ADT Design & Implementation
Lab 2: ADT Design & Implementation By Dr. Yingwu Zhu, Seattle University 1. Goals In this lab, you are required to use a dynamic array to design and implement an ADT SortedList that maintains a sorted
More informationCE221 Programming in C++ Part 1 Introduction
CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab
More information1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.
1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. B. Outputs to the console a floating point number f1 in scientific format
More informationProgramming C++ Lecture 2. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor
Programming C++ Lecture 2 Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Function Templates S S S We can do function overloading int boxvolume(int side) { return side
More informationCS1083 Week 3: Polymorphism
CS1083 Week 3: Polymorphism David Bremner 2018-01-18 Polymorphic Methods Late Binding Container Polymorphism More kinds of accounts DecimalAccount BigDecimal -balance: BigDecimal +DecimalAccount() +DecimalAccount(initialDollars
More informationCS 117 Programming II, Spring 2018 Dr. Ghriga. Midterm Exam Estimated Time: 2 hours. March 21, DUE DATE: March 28, 2018 at 12:00 PM
CS 117 Programming II, Spring 2018 Dr. Ghriga Midterm Exam Estimated Time: 2 hours March 21, 2018 DUE DATE: March 28, 2018 at 12:00 PM INSTRUCTIONS: Do all exercises for a total of 100 points. You are
More informationLesson Plan. Subject: OBJECT ORIENTED PROGRAMMING USING C++ :15 weeks (From January, 2018 to April,2018)
Lesson Plan Name of the Faculty Discipline Semester :Mrs. Reena Rani : Computer Engineering : IV Subject: OBJECT ORIENTED PROGRAMMING USING C++ Lesson Plan Duration :15 weeks (From January, 2018 to April,2018)
More informationFast Introduction to Object Oriented Programming and C++
Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming
More informationProgramming C++ Lecture 3. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor
Programming C++ Lecture 3 Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Inheritance S Software reuse inherit a class s data and behaviors and enhance with new capabilities.
More informationObject oriented programming
Exercises 12 Version 1.0, 9 May, 2017 Table of Contents 1. Virtual destructor and example problems...................................... 1 1.1. Virtual destructor.......................................................
More information[Page 177 (continued)] a. if ( age >= 65 ); cout << "Age is greater than or equal to 65" << endl; else cout << "Age is less than 65 << endl";
Page 1 of 10 [Page 177 (continued)] Exercises 4.11 Identify and correct the error(s) in each of the following: a. if ( age >= 65 ); cout
More information2 nd Week Lecture Notes
2 nd Week Lecture Notes Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous
More informationPROGRAMMING EXAMPLE: Checking Account Balance
Programming Example: Checking Account Balance 1 PROGRAMMING EXAMPLE: Checking Account Balance A local bank in your town is looking for someone to write a program that calculates a customer s checking account
More information