You are on page 1of 61

Program Layout: To include header files: #include <iostream> //at beginning of program All names defined in header file,

and belong to a namespace std using namespace std; If not using namespace, commands must be entered as std::cout << endl; Header of Main function: int main() Return at end of main function, The number 0 is called an integer, and int tells the compiler that the main function will be returning an integer value: return 0; We can describe the structure of a simple C++ program as: //Descriptive comment #include <StandardHeaderFile> using namespace std; int main( ) { StatementSequence; } Output Text: cout << Text Out; Output to next line: cout << endl; Set flag for ios fixed and digits after decimal point will be display: cout.setf(ios::fixed); Number of digits after decimal point is 2 (0.73) cout.precision(2); Output Escape Character: Tab: \t // Spaced 8 characters Newline: \n Double Quote: \ Backslash Char: \\ Change default width for next cout statement only: cout.width(10) Input Data: Waiting for enter cin >> variableName; cin.get(); //to be used after cin, remove one //keystroke <Enter> from input before //using getline. getline(cin, variable, \n); //\n =newline getline(cin, StringVariable, Delimiter); finalString = string1 + , + string2; cin >> input1 >> input2; cin >> charVal >> otherString;

Read line up to <Enter> Format of getline: Concatenate strings Input multi inputs Input Char and String Declare Variables: Integer Assign value in declare Constant integer program Float variable (0.123) String variable Character Value Boolean Value Bool assign Val One Dimensional Array

int intValue; int intValue=0; //can be changed in program const int INT_VALUE=0; //cannot be changed in float floatValue; string name; //to be used with #include <string> char charValue; bool result; bool result=false; int arrayVal[10];

Initialize during declare Two Dimensional Array Initialize during declare

int arrayVal[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int arrayVal[2][3]; //used for tables, row columns int arrayVal[][3]={1,2,3},{1,2,3};

Implicit conversion from int to float: floatValue = intValue; Explicit conversion from int to float: floatValue = float(intValue); Explicit conversion from float to int: intValue = int(floatValue); Explicit conversion from int to char: ASCIIVal = char(i); Explicit conversion from char to int: IntVal = int(charVal); String Manipulation: charVal=stringWord[charPos]; //{specific char in string} integerVal=stringWord.size( ); //{size of string} stringVal=stringWord.substr(fromPosToEnd); //{from pos to end} stringVal=stringWord.substr(fromPos, toPos);//{from pos to pos} integerVal=stringWord.find(oneWord); //{search string, -1 not found} integerVal=stringWord.find(oneWord, fromPos);//{search str from pos} stringWord.erase(fromPos, toPos); stringWord.insert(position, word2); stringWord.replace(fromPos, toPos, word2); getline(cin, stringWord, '\n'); Calculations: Increase by 1: Decrease by 1:

set set set set set

m m m m m

= = = = =

m m m m m

+ * / %

n n n n n

n++; n--; m = n++; //set m=n then increase n+1 m = ++n; //increase n+1 then set m=n m += n; m -= n; m *= n; m /= n; m %= n; // get leftover value from m / n

Value-returning functions: int abs(int) absolute value <cmath> int ceil(float) smallest integer greater than or equal to <cmath> float cos(float) cosine <cmath> float exp(float) exponential function <cmath> float fabs(float) floating point absolute value <cmath> int floor(float) largest integer less than or equal to <cmath> float log(float) natural logarithm <cmath> float log10(float) logarithm base 10 <cmath> float pow(float,float) power <cmath> int rand( ) random integer value from 0 to 32767 <cstdlib>

float sin(float) float sqrt(float) char tolower(char) char toupper(char) int time(int)

sine <cmath> square root <cmath> converts to lower case <iosctream> converts to upper case <iostrream> current time as a large positive integer <ctime>

Generating Random Number: srand(time(0)); //(seed random numbers with current date/time) randomInteger = interval * (rand( ) % many) + smallest; randomEvenNumbers = 2 * (rand( ) % 41) + 20;//(even ran 20-100) randomNumbers = 1 * (rand( ) % 101) + 0; //(rand 0-100=101 numb) // The smallest value generated by rand( ) % 21 is 0, so the smallest //value generated by 10 + rand( ) % 21 will be 10. The largest value //generated by rand( ) % 21 is 20, so the largest value generated by //10 + rand( ) % 21 will be 30
: s p o o L e l i h W

Statement is executed repeatedly while Condition is True. The only exit from the while loop occurs when Condition is False. while (Condition) //(pre-test loop) { Statement; Statement; } do { Statement; Statement; } while (Condition); //(post-test loop) Three aspects of the while: 1) Initializing the control variable 2) Testing the value of the control variable 3) Changing the value of the control variable Counter-driven while loops: count = 1; while (count <= 10) { cout << "Iteration number " << count << endl; count++; } Accumulation of a sum: count = 1; sum = 0; while (count <= 10) { cin >> value; sum += value;

count++; } Sentinel-driven loops: product = 1; cin >> value; while (value != 0) { product *= value; cin >> value; } Situation-driven loops: cin >> x; while (x != 1) { if (x % 2 == 1) x = x * 3 + 1; else x = x / 2; cout << x << endl; } A boolean loop control variable: again = true; while (again) { //Do something cout << "Do you want to do it again (Y/N)? "; cin >> answer; if (answer == 'n' || answer == 'N') again = false; } FOR LOOP Statements: for (int i = 1; i <= 10; i++) { Statement; } IF Statements: if (Condition) Statement1; else Statement2; Condition either be True or False: Boolean values: OR ||
AND &&

NOT
> >= < <=

!
is greater than is greater than or equal is less than is less than or equal

== !=

is equal is not equal

Separate if: if (Condition1) Statement1; if (Condition2) Statement2; Nested if: if (Condition1) Statement1; else if (Condition2) Statement2; else Statement3; The break statements that are used with switch: switch (day) { case 1: cout << "Sunday" << endl; break; case 2: cout << "Monday" << endl; break; case 3: case 4: cout << "Tuesday" << endl; //3, 4 result break; default: cout << "Invalid day" << endl; //no value found and default result } // Value of case must be singe character or value Return Functions: ReturnType FunctionName(ParameterList) //Declare function and return value to main { Statements; return ReturnValue; } // from main Result = FunctionName(ActualParameterList); //call function

Void Functions, value Parameter: void FunctionName(ParameterList) //Declare function, no return reverence { Statements; } // from main FunctionName(ActualParameterList); Void Functions, Reference Parameter: //update value of Actualparameter, using reference parameters. Normally is value //parameters void FunctionName(ParameterType & ParameterName) //use & to update reference parameter { Statements; } // from main FunctionName(ActualParameterList); //- If used with &, then Reference Parameter //- If not used with &, then Value Parameter Array parameters with functions: void inputArray(int arrayP[ ]) //declare reference Parameter { } int main( ) { int array[SIZE]; inputArray(array); return 0; } Multi-Dimension Array with functions: void showData(const int array[ ][secondVal]) //declare reference Parameter, only 2nd Array size //use const parameter not to change values in array { } int main ( ) { int firstArray[10][10];

showData(noiseData); //only send parameter return 0; }

Structs: struct StructName // create struct, Capital S { Type1 FieldList1; ! Type ArrayName[NUM_ELEMS]; TypeM FieldListM; }; //remember to add semicolon int main ( ) { StructName VariableName; //dclare variable VariableName.FieldList1 = value; //assign value VariableName.ArrayName[10] = value; //assisgn value to array } //to declare array of struct: struct StructName { Type1 FieldList1; ! TypeM FieldListM; }; int main ( ) { StructName structName1[arrayVal]; //array of struct variable declare structName1[arrayVal].FieldList1= value; //use in loop to update all arrays //Passing struct to functions: struct StructName //first declare struct variables { int variableName; } void function(StructName structVarP) //Value Parameter { structVarP.variableName = 1; } void function(StructName & structVarP) //Reference Parameter { structVarP.variableName = 1;

} main () { StructName structVarInMain; //declare variable from struct function(structVarInMain); //call function and send struct variables } //Can assign all values of one struct to another struct of the same type struct2 = struct1; Classes: class ClassName { public: MemberFunctionList; void inputData( ); private: DataMemberList; string dataVar; }; //remember the semicolon at end off class declare void ClassName::inputData( ) { getline (cin, dataVar, \n); } int main ( ) { ClassName name; name.inputData( ); } //inspector(view) and mutator(update) member functions of a class //There is a way to indicate and force a member function to be an inspector: we //add the reserved word const to the end of a member function header. For //example, to specify that displayData is an inspector we change the class //definition to class Movie { public: void inputData( ); void displayData( ) const; : etc. //and we change the member function definition to void Movie::displayData( ) const { cout << "Movie info" << endl; cout << "==========" << endl; ... etc.

// Processes a banking account and displays a monthly statement #include <iostream> using namespace std; const const const const float float float float DEPOSIT_FEE = 1.00; BALANCE_FEE = 0.50; WITHDRAWAL_FEE = 1.50; OVERDRAWN_FEE = 5.00;

struct Transaction { char type; float amount; }; const int MAX_TRANSACT = 30; class Account { public: Account( ); void deposit(float a); float balanceEnquiry( ); void withdrawal(float a); void displayStatement( ) const; private: float balance; Transaction transacts[MAX_TRANSACT]; int numTransacts; float feeTotal; }; Account::Account( ) { balance = 0; numTransacts = 0; feeTotal = 0; } void Account::deposit(float a) { balance += a; feeTotal += DEPOSIT_FEE; balance -= DEPOSIT_FEE; transacts[numTransacts].type = 'D'; transacts[numTransacts].amount = a; numTransacts++; }

float Account::balanceEnquiry( ) { feeTotal += BALANCE_FEE; balance -= BALANCE_FEE; transacts[numTransacts].type = 'B'; transacts[numTransacts].amount = 0; numTransacts++; return balance; } void Account::withdrawal(float a) { balance -= a; if (balance >= 0) { feeTotal += WITHDRAWAL_FEE; balance -= WITHDRAWAL_FEE; } else { feeTotal += OVERDRAWN_FEE; balance -= OVERDRAWN_FEE; } transacts[numTransacts].type = 'W'; transacts[numTransacts].amount = a; numTransacts++; } void Account::displayStatement( ) const { cout << endl << "Monthly Statement" << endl; cout << "=================" << endl; for (int i = 0; i < numTransacts; i++) { switch (transacts[i].type) { case 'D': cout << "Deposit\tR" << transacts[i].amount << endl; break; case 'B': cout << "Balance enquiry" << endl; break; case 'W': cout << "Withdrawal\tR" << transacts[i].amount << endl; break; } } cout << "Total Fee\tR" << feeTotal << endl; cout << "---------------------------------" << endl; cout << "Closing balance\tR" << balance << endl; } int main( ) { Account account1;

char type; float amount; cout << "Enter the transactions for the month" << endl; cout << "(D)eposit, (B)alance enquiry, (W)ithdrawal, E(X)it:" << endl; cin >> type; while (toupper(type) != 'X') { switch(toupper(type)) { case 'D': cin >> amount; account1.deposit(amount); break; case 'B': account1.balanceEnquiry( ); break; case 'W': cin >> amount; account1.withdrawal(amount); } cin >> type; } cout << endl; account1.displayStatement( ); return 0; }

Programming 2 Streams and basic I/O: Declaring streams: Type ifstream and ofstream are defined in library fstream. #include <fstream> //declaring stream variables ifstream in_stream; ofstream out_stream; //streams must be connected to a file in_stream.open(infile.dat); //input from file using >> operator (same as cin for input from keyboard) int one_number, another_number; instream >> one_number >> another_number; //output stream defined same as inputstream ofstream out_stream; out_stream.open(outfile.dat); // open file + create if it does not exist. If file has contents, member function // will discard data and output file will be empty. // using insert << operator to write to the file out_stream << one_number = << one_number << another_number = << another_number; The external file name is given as argument to the function open, but after the file is opened, the file is always referred to by naming the stream that is connected to the file. // Every file must be closed when program is finnsihed with it in_stream.close(); out_stream.close(); // if program end normal the system will also automaticly close the file // create file for testing # include <fstream> using namespace std; int main() { ifstream in_stream; ofstream out_stream; int first, second, third; in_stream.open("infile.dat"); out_stream.open("outfile.dat"); in_stream >> first >> second >> third; //reading line for line from file out_stream << "the sum of the first 3\n" //note next line for output to file

The streams in_stream and out_stream and the predefined streams cin and cout are objects. A function associated with an object is called a member function. Example .open is a member function of the object in_stream. class type whose variables are objects such as ifstream and ofstream The class ofstream also has a member function precision (same as for cout) When call member function in program, specify an object writing the object name and a dot before the function name in_stream.open(infile.dat); Dot is called dot operator and the object name before the dot is referred to as the calling object.

PROGRAMMING TIP Check if file was opened successfully (call to open file might be unsuccessful and program could continue giving error results) // use member function fail to test if stream operation has failed. Reurns bool // value. in_stream.fail() // should be done after each open call. If call fail, function will return bool true. in_stream.open(stuff.dat); if (in_stream.file()) { cout << Input file opening failed.\n; exit(1); //Ends the program } To use exit function program must include directive: #include <cstdlib> Function exist is predefined function taking single integer argument. By convention, 1 used as argument if call to exit due to error, and 0 used otherwise.

Append to file (Optional). To append output to file already with data, use two-argument version of open ofstream outStream; outStream.open(file.txt, ios:app); If file does not exist, it will create an empty file with name received. Old data in file is not lost. Argument ios:app is special constant defined in iostream, so required to include #include <iostream> Using namespace std;

File Names as Input (Optional) File name is String (sequence of characters) which can be used with cin to enter a file name. To use the string, char variable to hold value char file_name[16]; // must be string length + 1, so for 15 char use 16 cout << Enter file name (max 15 char):\n; cin >> file_name; cout << OK, edit the file << file_name << endl; in_stream.open(file_name); //Open file if (in_stream.fail()) //Check if file opening was successful { cout << Input file opening failed.\n; exit(1); } Use same commands in cout to ensure numbers with decimal point will be written in the correct format. out_stream.setf(ios::fixed); out_stream.setf(ios::showpoint); out_stream.precision(2);

Formatting Flags for setf ios:fixed If flag set, floating-point numbers are not set written in e-notation ios::scientific If flag set, floating-point numbers are written set in e-notation. ios::showpoint set

Defaultnot

Default-not

If set, decimal point traailing zeros are always Default-not shown for floating-point numbers. If not set, number with all xeros after decimap point might output without the decimal point and following zeros.

ios::showpos set

If flag is set, a plus sign is output before positive integer value

Default-not

ios::right

If flag is set and some field-width value is given with a call to member function width, then next item output will be at right end of space specified by width. Extra blanks are placed before item output. (Setting this flag automatically unset flag ios::left) If flag is set and some field-width is given

Default-set

ios::left set

Default-not

with a call to the member function width, then next puput will be at left end of space specified by width. Any extra blanks are placed after the item output. (Setting this flag automatically unset flag ios::right) width commonly used formatting function. cout << Start Now; cout.width(4); cout << 7 << endl; This will result following appear on screen Start Now 7 This output has three spaced between letter w and the number 7. The number 7 occupy one space If output requires more space than specified, additional space as needed will be used. Only applies to next output unsetf Flag set may be unset. cout.unsetf(ios::showpos);

Manipulator function called in nontraditional way. Are placed after insertion operator <<. setw same as function width cout << Start << setw(4) << 10 << setw(4) << 20 << setw(6) << 30; (Two spaces before the 10, two before the 20 and four before the 30) setprecision same as function precision cout.setf(ios::fixed); cout.setf(ios::showpoint); cout << $ << setprecision(2) << 10.3 << endl << $ << 20.5 << endl; To use manipulators setw and setprecision need to include directive #include <iomanip> using namespace std; PROGRAMMING TIP Checking for End of a File (in_stream >> next) // boolean expression if end of file this will be false Example:

double next, sum = 0; Int count = 0; while (in_stream >> next) { sum = sum + next; count++; } Note the loop body in_stream >> next is now boolean and also input value. It is now input number from file and controlling boolean expression for the while loop. Technically this is overloading of operator >> for the input stream class. Member functions get and put char next_symbol; cin.get(next_symbol); //read next input character Detecting the end of an input line: cout << Enter line of input:\n; char symbol; do { cin.get(symbol); cout << symbol; } while (symbol != \n); Also to read from file: in_stream.get(next_symbol); Member function put take one argument of expresion char and output. cout.put(a); Also to write one char to file: out_stream.put(Z); Member function putback is used for when need to know next charactr in the inputstream, but turn out not to be processed this character. Example program read up to but not including a certain character. fin.get(next); while (next != ) { fout.put(next); fin.get(next); } fin.putback(next); Note putback place a character in an input stream, while put place character in output stream.

The eof Member function Every input-file stream has member function called eof that can be used to determine when all of the file has been read and no more input left. fin.eof(); //return boolean expression if (! Fin.eof()) cout << Not done yet.; else

cout << end of file found; // used in while loop In_stream.get(next); While (! In_stream.eof()) { Cout << next; In_stream.get(next); } Pitfall toupper and tolower cout << toupper(a); // output number assigned to A Instead should use: char c = toupper(a); //Place A in variable c cout << c; Some Predefined Character Functions in cctype

POINTERS: Pointer is the memory address of a variable. Pointer can be stored in a variable. Though pointer is memory address and address is a number, cannot store pointer in variable type int or double. Variable to hold pointer must be declared to have pointer type. Following declares p to be pointer variable that can hol one pointer that points to variable of type double. double *p; Variable of type double cannot contain pointer to other variable type. Each variable type requires different pointer type. Int *p1, *p2, v1, v2; //declare 2 pointer and 2 normal int variables p1 = &v1; //determain address of v1 and assign to pointer value to p1 // note the & operator Two ways to refer to v1: call v1 or call variable pointed to by p1 v1 = 0; p1 = &v1; //assign address of v1 *p1 = 42; //assign value to variable pointed to by p1 cout << v1 << endl; cout << *p1 << endl; //Result output is saame value 42 p2 = p1; //copy address value from one pointer to the other *p2 = *p1; //copy value of pointer address new Operator new can be used to create variables that have no identifiers to serve as their names. These nameless variables are referred to via pointers. p1 = new int; // create new variable of type int and set pointer // variable p1 equil to the address of this variable. // p1 points to nameless int variable. // Variable now used as normal int: cin >> *1p1; *p1 = *p1 + 7 cout << *p1; delete eliminate dynamic variable and return the memory ocupied by the variable. delete p; PROGRAMMING TIP can define pointer type name so pointer variable can be declared like other variables. typedef int* IntPtr; // following would declare same: IntPtr p; // same as: int *p; // declare mutilple: IntPtr p1, p1; // ass oposed to int *p1, *p2; Use typedef to define alias for any type name or definition. typedef double Kilometers; Kilometers distance;

DYNAMIC ARRAYS: Array variables are actually pointer variables. Dynamic Array is an array whose size is not specified when writing program, but is determined while program is running. Array is pointer variable that points to first indexed variable of array. int a[10]; typedef int* IntPtr; IntPtr p; p = a; // assign value of a to p, p pointing to same location p[0], p[1], p[2]... p[9] //square bracked for array apply to pointer Note cannot change pointer value in array variable. IntPtr p2; a = p2; // ILLEGAL cannot assign different address to a; Array need to specify size during declaration when writing the program. May leed to estimate size too low causing program not to work Dinamic array avoid this problem. Size is determained during runtime when size can be input with program. Dinamic array is created using new operator. typedef double* DoublePtr; DoublePtr p; p = new double[10]; delete [] p; Example: int array_size; cout << How many numbers will be sorted? ; cin >> array_size; IntArrayPtr a; a = new int[array_size]; delete [] a; // if omit brackets only one varialbe int is deleted

Struct CDAccount { double balance; double interest_rate; int term; //months until maturity };

Structures as Function Arguments


Function can have call-by-value parameters of a structure type and/or call-byreference parameters of structure type. Structure type can also be type for value returned by function. Exmple defines function teking three arguments and returns value of type CDAccount. CDAccount shrink_wrap(double the_balance, double the_rate, int the_term) { CDAccount temp; temp.balance = the_balance; temp.interest_rate = the_rate; temp.term = the_term; return temp; } Use Hierarchical Structures Can have structures whose members are themselves smaller structures. struct Date { int month; int day; int year; }; struct PersonInfo { double hight; int weight; date birthday; }; Structure variable of type PersonInfo is declared in usual way: PersonInfo person1; cout << person1.birthday.year;

Initializing Structures
Can initialize structure at time it is declared: struct Date { int month; int day; int year; }; Once type Date is defined, can declare and initialize structure variable: Date due_date = {12, 31, 2004};

CLASSES
class DayOfYear { public: void output(); // Member function declared int month; int day; }; void DayOfYear::output() // Member function definition { cout << month = << month << , day = << day << endl; } int main () { DayOfYear today, birthday; cout << Enter todays date:\n; cout << Enter month as number: ; cin >> totday.month; cout << Enter day of month: ; cin >> today.day; cout << Totdays date is ; today.output(); // call to member function output public: list of members changes from private to public private: list of members changes back to being private members class SmpleClass { public: void do_somethin(); int stuff; private: void do_somethin_else(); char more_stuff; public: double do_yet_another_thing(); double even_more_stuff; };

Name of member function for class may be overloaded just like name of ordinary function Class my use another class as type for member variable Function may have formal parameters whose types are classes Function may return an object; that is, a class may be type for value return by a function

Constructors for Initialization


1) Constructor must have same name as the class. 2) Constructor definition cannot return a value. No return type or void can be given at start of function declaration or in function header class BankAccount { public: BankAccount(int dollrsa, int cents, double rate); // Initialize account balance to #dollrs, cents and initialize interest void set(int dollars, int cents, double rate); void set(int dollars, double rate); void update(); double get_balance(); double get_rate(); void output(ostream & units); private: double balance; double interest_rate; double fraction(double percent); }; With redefined class BankAccount, two objects of type BankAccount can be declared and initialized as follow: BankAccount account1(10, 50, 2.0), account2(500, 0, 4.5);

Definition of consturctor is given in same way as any other member function. Example if revise definition of class BankAccount by adding constructor described, also add following definition of constructor: BankAccount::BankAccount(int dollars, int cents, double rate) { if ((dollars < 0) || (cents < 0) || (rate < 0)) { cout << Illegal values for money or interest rate. \n; exit(1); } balance = dollars + 0.01*cents; interest_rate = rate; } Can overload constructor name BankAccount::BankAccount as any other member function name.

Constructor
Constructor is a member function of a class that has same name as the class. Constructor is called automatically when object of class is declared. Constructors are used to initialize objects. Constructor must have same name as class of which it is a member. //Class for bank account: class BankAccount { public: BankAccount(int dollars, int cents, double rate); //Initializes the account balance to $dollars.cents and initializes //interst rate to rate percent. BankAccount(int dollars, double rate); //Initializes the account balance to $dollars.00 and //initializes the interest rate to rate percent. BankAccount(); //Default constructor //Initializes the account balance to $0.00 and interest rate to 0.0% }; BankAccount::BankAccount(int dollars, int cents, double rate) { if ((dollars < 0) || (cents < 0) || (rate < 0)) { cout << Illegal values for money or interest rate.\n; exit(1); } balance = dollars + 0.01*cents; interest_rate = rate; } BankAccount::BankAccount(int dollars, double rate) { if ((dollars < 0) || (rate < 0) { cout << Illegal values for money or interest rate.\n; exit(1); }

balance = dollars; interest_rate rate; } BankAccount::BankAccount() : balance(0), interest_rate(0.0) { //Body empty } int main() { BankAccount account1(100, 2.3), account2;//declaration call cout << account1 initialized as follows:\n; account1.output(cout); cout << account2 initialized as follow:\n; account2.output(cout); account1 = BankAccount(999, 99, 5.5); //explicit call to constructor cout << account1 reset to following:\n; account1.output(cout); return 0; } Constructor with no parameters contains somethin new. BankAccount::BankAccount() : balance(0), interest_rate(0.0) { //Body empty } Eqivilant to: BankAccount::BlankAccount() { Balance = 0; Interest_rate = 0.0; }

Constructor Initialization Section


Member variables in a class can (optionally) be initialized in constructor initializtion section of constructor definition. Constructor initialization section goes after parentheses that ends parameter list and before opening brace of the function body. Initialization section consists of a colon followed by list of some or all member variables separated by commas. Each member variable is followed by its initializing value in parenthese. Example use a constructor initialization section and equivalent to the threeparameter constructor: BankAccount::BankAccount(int dollars, int cents, double rate) : balance(dollars + 0.01*cents), interest_rate(rate) { if ((dollars < 0) || (cents < 0) || (rate <0)) { cout << Illegal values entered.\n; exit(1); } }

Calling a Constructor
Constructor is called automatically when an object is declared, but must give the arguments for constructor when declare the object. Constructor can also be called explicitly in order to create new object for class variable. Syntax (for object declaration when have constructors) Class_Name Object_Name(Asguments_for_Constructor); Example: BankAccount account1(100, 2.3); Syntax (for explicit constructor call) Object = Constructor_Name(Arguments_For_Constructor); Example: Account1 = BankAccount(200, 3.5); Constructor must have same name as class of which it is a member. Class_Name and Constructor_Name are same identifier Always include Default Constructor C++ does not always generate a default constructor for classes defined. If give no constructor, the compiler will generate default constructor that does nothing. This constructor will be called if class objects are declared. If at leat one constructor is defined for a class, C++ compiler will generate no other constructors. Everytime declare an object of that type, C++ will look for appropriate constructor definition to use. If declare object without using arguments for constructor, C++ will look for a default, and if not defined, default constructor, none will be found. Example: class SampleClass { public: SampleClass(int parameter1, double parameter2); //construct requires //2 arguments Void do_stuff(); private: int data1; double data2; }; Following legel way to declare object tpye SampleClass and call constructor for that class: SampleClass my_object(7, 7.77); However, following is illegal: SampleClass your_object; Compiler interprets declaration as including call to constructor with no arguments, but there is no definition for constructor with zero arguments. Must either add two arguments to declaration your_object or add constructor definition for constructor with no arguments. Constructor called with no arguments is called default constructor, since applies in default case where declare object without specifying any arguments. Class SampleClass { Public: SampleClass(int parameter1, double parameter2); SampleClass (); //Default constructor

If do not want default constructor to initialize any member variables, give empty body when implemented. It does nothing when called acept satisfy compiler. SampleClass::SampleClass() { //Do Nothing } Constructors with No Arguments If constructor for class BankAccount has two formal parameters, declare an object and give arguments to constructor: BankAccount account1(200, 2.3); To call constructor with no arguments, would declare object as: BankAccount account2(); //THIS WILL CAUSE PROBLEMS When call function with no arguments, include pair of empty parentheses. However, this is wrong for constructor. It may not produce error message, since does not have unintended meaning. Correct way to declare account2 using constructor with no arguments: BankAccount account2; If explicitly call constructor in assignment, do use parentheses. Following set account balance to $0.00 and rate to 0.0%: Account1 = BankAccount();

Abstract Data Type


Data type is abstract data type (ADT) if programmer using this type do not have access to details of how values and operations are implemented. Do not know how operations like + or * are implemented when using type int. Classes to Produce Abstract Data Type Class is type you define, as appose to type such as int and char. Value of class type is set of values of member variables. Example value for type BankAccount consists of 2 numbers of type double. Class BankAccount { public: BankAccount(int dollars, int cents, double rate); BancAccount(int dollars, double rate); BankAccount(); void update(); double get_balance(); double get_rate(); void output(ostream& outs); private: double balance; double interest_rate; double fraction(double percent); }; Programmer using BankAccount need not know how implemented definition of BankAccount::update or any other member functions. Function definition for member function BankAccount::update void BankAccount::update() { Balance = balance + fraction(interest_rate)*balance; }

Could have dispensed with private function fraction and implemented member function update: void BankAccount::update() { Balance = balance + (interest_rate/100.0)*balance; } Using class BankAccount net not concern with which implementation of update used, since both implementations have same effect. Similarly using class BankAccount neet not concern about how values of class are implemented. Chose to implement values as two values of type double. If vacation_savings is object of type BankAccount, value of vacation_savings consists of two values of type double stored in following member varibles: vacation_savings.balance vacation_savings.interest_rate However, do not want to think of value of object vacation_savings as two numbers of type double, such as 1.3546e+2 and 4.5 Value of vacation_savings as single entry Account balance $135.46 Interest rate 4.5% This is why BankAccount::output writes class value in this format. Chose to implement BankAccount value as two double values 1.3546e+2 and 4.5 as implementation detail. Could instead have BankAccount value as two int values 135 and 46 (for dollars and cents part of balance) and single value 0.045 of type double. Value 0.045 is simply 4.5% converted to fraction. With alternative implementation of class BankAccount, public members would remain unchanged but private members would change: { public: <This part is exactly as before> private: int dollars_part; int cents_part; double interest_rate; double fraction(double percent); }; Need to change member function definitions to mach. double BankAccount::get_balance() { return(dollars_part + 0.01*cents_part); } BankAccount::BankAccount(int dollars, int cents, double rate) { if ((dollars < 0) || (cents < 0) || (rate < 0)) { cout << Illegal value for money or interest rate.\n; exit(1); } dollars_part = dollars; cents_part = cents; interest_rate = rate; }

How to write an ADT In order to define a class so that it is an abstract data type, need to separate the specification of how the type is used by programmer from details of how the type is implemented. Separation should be complete to change implementation of the class without need to make any changes in any program that use the class ADT. 1) Make all memver variables private members of the class. 2) Make each operation neede a public member function of the class, and fully specify how to use each public member function. 3) Make helping functions private member functions. Interface of ADT tell you how to use ADT in program. When define ADT as C++ class, interface of public member function of class along with comments that tell how to use these public functions. Program example Data of bank account is implemented as three member values: dollars part of account balance, cents part of account balance and interest rate. Note value of interest_rate 0.047 as fraction //Alternative implementation of class BankAccount: #include <iostream> #include <cmath> Using namespace std; //Class for bank account class BankAccount { public: BankAccount(int dollars, int cents, double rate); //Initialize account balance to $dollars.cents and //initialize interest rate to rate percent. BankAccount(int dollars, double rate); //Initialize account balance to $dollars.00 and //Initialize interest rate to rate percent. BankAccount(); //Initialize account balance to $0.00 and interest rate to 0.0% void update(); //Postcondition: One year interest added to account balance double get_balance(); //Return current account balance double get_rate(); //Return current interest rate as percentage void output(ostream& outs); //Precondition: if outs is file output, then outs has already //connected to a file. //Postcondition: Account balance and interest rate written to stream //outs private: int dollars_part; int cents_part; double interest_rate;//as fraction, 0.057 for 5.7% double fraction(double percent);//convert percentage to fraction 5.7% to //0.057 double percent(double fraction_value);//convert fraction to percent };//end of class, remember semicolumn.

BankAccount::BankAccount(int dollars, int cents, double rate) { if ((dollars < 0) || (cents < 0) || (rate < 0)) { cout << Illegal values for money or interest rate.\n; exit(1); } dollars_part = dollars; cents_part = cents; interest_rate = fraction(rate); } BankAccount::BankAccount(int dollars, double rate) { if ((dollars < 0) || (rate < 0)) { cout << Illegal values for money or interest rate.\n; exit(1); } dollars_part = dollars; cents_part = 0; interest_rate = fraction(rate); } double BankAccount::fraction(double percent_value) { return (percent_value/100.0); } //Using cmath void BankAccount::update() { double balance = get_balance(); balance = balance + interest_rate*balance; dollars_part = floor(balance); cents_part = floor((balance dollars_part)*100); } double BankAccount::get_balance() { Return(dollars_part + 0.01*cents_part); } double BankAccount::percent(double fraction_value); { Return (fraction_value*100); } double BankAccount::get_rate() { Return percent(interest_rate); } //Using iostream: void BankAccount::output(ostream& outs) { outs.setf(ios::fixed); outs.setf(ios::showpoint); outs.precision(2); outs << Account balance $ << get_balance() << endl; outs << Interest rate << get_rate() << % << endl; }

int main() { BankAccount account1(100, 2.3), account2; cout << account1 initialized as follow:\n; account1.output(cout); cout << account2 initialized as follow:\n; account2.output(cout); account1 = BankAccount(999, 99, 5.5); cout << account1 rest to following:\n; account1.output(cout); return 0; }

Introduction to Inheritance
When one class was derived from another class, the derived class was obtained from from the other class by adding features. Example: class of input-file streams is derived from class of all input streams by adding member functions, such as open and close. Stream cin belongs to class of all input streams, but does not belong to class input-file streams beacause cin has no member functions named open and close. Stream declared to be type ifstream is an input-file stream because it has added member functions open and close. Inheritance among stream classes: Object is a variable that has member functions, and class is type whose variables are objects. Streams (like cin, cout, input-file and output-file streams) are objects, so stream types, such as ifstream and ofstream, are classes. Consider function, which read 2 integers from input stream source_file and writes sum to screen: void two_sum(ifstream& source_file) { int n1, n2; source_file >> n1 >> n2; cout << n1 << + << n2 << = << (n1 + n2) << endl; } Suppose program contains previous function definition and following stream declaration: ifstream fin; If fin is connected to file with call to open, can use function two_sum to read two integers from file and write sum to screen. The call would be: two_sum(fin); In same program, can change program to read two numbers from keybord and write their sum to screen. Since all input streams are similar, might think can use cim: two_sum(cin); //THIS WILL NOT WORK cin is not of type ifstream; cin is of type istream (without the f). If using cin as argument to function, corresponding function parameter should be of type istream.

Rewritten to accept cin as argument: void better_two_sum(istream& source_file) //instead of ifstream as before { int n1, n2; source_file >> n1 >> n2; cout << n1 << + << n2 << = << (n1 + n2) << endl; } Function call: better_two_sum(cin); Function better_two_sum can be used with any kind of input stream. Also following is legal: better_two_sum(fin); fin is of type ifstream and argument is of type istream.Stream fin has two types. Type ifstream is delivered class of istream. It means ifstream class has all features of class istream including the added features. Stream cin is of type istream and not of type ifstream, so cannot use cin with function open. Example: function new_line has formal parameter of type istream for input //using iostream void new_line(istream& in_stream) { char symbol; do { in_stream.get(symbol); }while (symbol != \n); } If program is taking input from input stream call fin (connected to input file) following will discard all input left on line currently being read from input file: new_line(fin); If also reading input from keybord, following will discard remainder of input line that was typed by keyboard: new_line(cin); Following are equivelant: new_line(); Example: Derive CDAccount class from BankAccount class. Specify relationship when defining derived class by adding colon followed by keyword public and name of parent or base class: class CDAccount : public BankAccount { public: CDAccount(int dollars, int cents, double rate, int days_to_maturity); <Other constructors follow here> int get_days_to_maturity(); //Return number of days until CD mature void decrement_days_to_maturity(); //Subtract one from days_to_maturity private: int_days_to_maturity; //Days until CD matures };

Only define functions and data specifically related to CD accounts, storing and manupilating number of days to maturity. Do not need to redefine all variables ralated to bank accounts.This is inherited from BankAccount object. Example if create CDAccount object, could invoke functions: CDAccount newCD(1000, 0, 6.0, 180); //New CD Account with $1000, 6% interest, mature 180 days days_tomaturity = newCD.get_days_to_maturity();//return 180 balance = newCD.get_balance(); //Return 1000

11 Friends, Overloaded Operators, and Arrays in Classes Friend Function


Class operations, such as input, output, accessor functions have been implemented as member functions of the class, but for some operations, it is more natural to implement operations as ordinary (non-member) functions. Example: added function equal that can test two object types of type DayOfYear to see if values represent same data. //program to demonstrate function equal. #include <iostream> using namespace std; class DayOfYear { public: DayOfYear(int the_month, int the_day); //Precondition: the_month and the_day form possible date. Initialize //date according to arguments. DayOfYear(); //Initialize date to Junuary first. void input(); void output(); int get_month(); //Return month, 1 for January, 2 for February, ect. int_get_day(); //Return day of month private: void check_date(); int month; int day; }; Bool equal(DayOfYear date1, DateOfYear date2); //Precondition: date1 and date2 have values //Return true if date1 and date2 represent same date //Otherwise return false { return(date1.get_month() == date2.get_month() && date1.get_day() == date2.get_day()); } DayOfYear::DayOfYear(int the_month, int the_day) : month(the_month), day(the_day)

{ Check_date(); } int DayOfYear::get_month() { return month; } Int DayOfYear::get_day() { return day; } //Using iostream void DayOfYear::input() { cout << Enter month as nunmber: ; cin >> month; cout << Enter day of the month: ; cin >> day; } //Using iostream void DayOfYear::output() { cout << month = << month << , day = << day << endl; } Int main() { DayOfYear today, bach_birthday(3, 21); cout << Enter totdays date:\n; today.input(); cout << Todays date is: ; today.output(); cout << J.S. Bach birthdate is ; bach_birtday.output(); if(equal(today, bach_birthday)) cout << Happy Birthday!\n; else cout << Happy Un-Birthday!\n; return 0; }

Friend Functions
If class has full set of accessor functions, can use accessor define function to test equality or do computing that depends variables. From above, function of equal to read the month it accessor function get_month. To read day it must make call to get_day. Simpler form would be to access member variables. bool equal(DayOfMonth date1, DayOfMonth date2) { return (date1.month == date2.month && date1.day == } funtions to on private member must make call to accessor function

date2.day);

This would be illegal since day and month are private members of class DayOfYear. To make this legal, make function equal a friend of the class DayOfYear, then above definition of equal would be legal. Friend function of a class is not a member function of the class, but friend function has access to the private members of the class just as the member function does. class DayOfYear { public: friend bool equal(DayOfYear date1, DayOfYear date2) }; bool equal(DayOfYear date1, DayOfYEar date2) // private variable can now //be accessed 1) Use member function if task performed by function involves only one object 2) Use nonmember function if task performed involves more than one object.

Overloading Operators
Can overload operator + (and any other operations) to accept arguments of class type. class Money { public: friend Money operator +(const Money& amount1, const Money& amount2); friend Money operator ==(const Money& amount1, const Money& amount2); }; Money operator +(const Money& amount1, const Money& amount2) { Money temp; temp.all_cents = amount1.all_cents + amount2.all_cents; return temp; } Money operator ==(const Money& amount1, const Money& amount2) { return(amount1.all_cent == amount2.all_cents); } int main() { total = cost + tax; if (cost == tax) cout <<text; return 0; }

Constructors of Automatic Type Conversion


class Money { public: ... Money(double amount); // Initializes object so its value represent $amount

Overloading Unary Operators


In additioin to binary operations, there are many unary operators (++ -- << >>) Can overload ++ and - similarly. As in ++x and x- are handle different. << is an operator: cout << Hello world; class Money { public: . . . friend ostream& operator <<(ostream& outs, const Money& amount); }; ostream& operator <<(ostream& outs, const Money& amount); { return outs; } Result: cout I have << amount << in my purse.\n; means the same as: ((cout << I have ) << amount) << in my purse.\n; And is evaluated as follow: First evaluate (cout << I have ), which means cout: ((cout << I have ) << amount) << in my purse.\n; And the string I have is output. (cout << amount) << in my purse.\n; Then evaluate (cout << amount), which returns cout: (cout << amount) << in my purse.\n; And the amount is output cout << in my purse.\n; Then evaluate cout << in my purse.\n, which return cout: cout << in my purse.\n; and the string in my purse.\n is output cout; since no more << operators, process ends Example: //Program demontrate class Money #include <iostream> #include <fstream> #include <cstdlib> #include <cctype> using namespace std; //Class for amounts of money in $ class Money { public: friend Money operator +(const Money& amount1, const Money& amount2); friend Money operator -(const Money& amount1, const Money& amount2); friend Money operator -(const Money& amount); friend Money operator ==(const Money& amount1, const Money& amount2); Money(long dollars, int cents); Money(long dollars); Money();

double get_value() const; friend istream& operator >>(istream& ins, Money& amount); //Overloading the >> so it can be used to input values of type // Money. //Notation for inputting negative amounts is as in -$100.00 //Precondition: If ins is file input stream, then ins has already //been connected to a file. friend ostream& operator <<(ostream& outs, const Money& amount); //Overloading the << operator so it can be used to output values of //type Money. //Precedes each output value of type Money with a Dollar Sign. //Precondition: If outs is a file output stream, then outs has //already been connected to a file private: long all_cents; }; istream& operator >>(istream& ins, Money& amount); //Use iostream, cctype and cstlib; { char one_char, decimal_point, digit1, digit2; //digits for amount of cents long dollas; int cents; bool negative ;//set to true if input negative ins >> one_char; if (one_char == -) { negative = true; ins >> one_char; //read $ } else negative =false; //if input is legal, then one_char ==$ ins >> dollars >> decimal_point >> digit1 >> digit2; if(one_char != $ || decimal_point != . || !isdigit(digit1) || !isdigit(digit2)) { cout << Error illegal form for money input.\n; exit(1); } cents = digit_to_int(digit1)*10 + digit_to_int(digit2); amount.all_cents = dollars*100 + cents; if (negative) amount.all_cents = -amount.all_cents; return ins; } int digit_to_int(char c); //Used in the definition of the overloaded input operator >>. //Precondition: c is one of the digits 0 through 9.

//Returns the integer for the digit; example, digit_to_int(3) returns 3. { Return(static_cast<int>(C) static_cast<int>(0)); } friend ostream& operator <<(ostream& outs, const Money& amount); //Use cstlib and iostream { long positive_cents, dollars, cents; positive_cents = labs(amount.all_cents); dollars = positive_cents/100; cents = positive_cents%100; if (amount.all_cents < 0) outs << -$ << dollars << .; else couts << $ << dollars << .; if (cents < 10) out << 0; outs << cents; return outs; } int main() { Money amount; ifstream in_stream; ofstream out_stream; in_stream.open(infile.dat); if(in_stream.fail()) { cout << Input file opening failed.\n; exit(1); } out_stream.open(outfile.dat); if(out_stream.fail()) { cout << Ouput file opening failed.\n; exit(1); } in_stream >> amount; out_stream << amount << copied from the file infile.dat.\n; cout << amount << copied from the file infile.dat.\n; in_stream.close(); out_stream.close(); return 0; }

ARRAYS and CLASSES


Can combine arrays, structures and classes to form intricately structured type such as arrays of structures, arrays of classes and classes with arrays as members variables. Base type of array may be any type, including types that you define, such as structures and class types. If want each indexed variable to contain items of different types, make array an array of structures. struct WindInfo { double velocity; // in miles per hour char direction; //N, S, E, W }; WindInfo data_point[10]; int i; for (i = 0; i < 10; i++) { cout << Enter velocity for << i << number data point: ; cin >> data_pointp[i].velocity; cout << Enter direction for data point: << (N, S, E, W): ; cin >> data_point[i].direction; } Array as Class Members: Can have structure or class that has an array as a member variable. struct Data { double time[10]; int distance; }; Data my_best; Example: #include <iostream> #include <cstlib> using namespace std; const int MAX_LIST_SIZE = 50; class TemperatureList { public: TemperatureList(); //Initialize the object to an empty list. void add_tempreture(doubl tempreture); //Precondition: The list is not full //Postcondition: Tempreture has been added to the list bool full() const; //return true if list is full; false otherwise

friend ostream& operator << (ostream& outs, const TempretureList& the_object); //Overloading the << operator so it can be used to output values of //type TempretureList. Temperatures are output one per line . //Precondition: If outs is a file output stream, then outs //has already been connected to a file. private: double list[MAX_LIST_SIZE]; //of tempretures in Fahrenheit. int size; //number of array positions filled }; Temperature::TemperatureList():size(0) { //Body empty } void TemperatureList::add_temperature(double temperature) {//use iostream and cstlib if (full()) { cout << Error: adding to full list.\n; exit(1); } else { list[size]=temperature; size = size + 1; } } bool TempretureList::full()const { return(size == MAX_LIST_SIZE); } ostream& operator << (ostream& outs, const TemperatureList& the_object) { for (int i = 0; i < the_object.size; i++) outs << the_object.list[i] << F\n; return outs; }

CLASSES and DYNAMIC ARRAYS


Dynamic array can have base type that is a class. Class can have member variable that is dynamic array. Can combine techniques about classes and techniques from dynamic arrays. Example: One constructor for class StringVar takes single argument of type int. This argument determines the maximum allowable length for a stringvalue stored in the object. Default constructor creates an object with maximum allowable length of 100. Another constructor takes an array argument that contains a C string. Note argument to this constructor can be quoted string. This constructor initializes the object so that it could hold any string less than 100 length

//Thi is the definition for the class StringVar whose values are string. An //object is declared as follow //Note that you use (max_size), not [max_size] // StringVar the object(max_size); //where max_size is the longest string length allowed. #include <iostream> using namespace std; class StringVar { public: StringVar(int size); //Initialize object so it can accept string values up to size in //length. Sets the value of the object equal to the empty string. StringVar(); //Initialize object so it can accept string values of length 100 or //less. Sets the value of the object equal to the empty string. StringVar(const char a[]); //Precondition: The array a contains characters terminated with \0 //initializes the object so its value is the string stored in a and //so that it can later be set to string values up to strlen(a) in //length StringVar(const StringVar& string_object); //Copy constructor ~StringVar(); //Returns all the dinamic memory used by object to freestore int length() const; //Returns the length of current string value void input_line(istream& ins); //Precondition: if ins is file input stream, ins must be connected //to file. //Action: Next text in input stream ins, up tp \n, is copied //to calling object. If insuffecient room, only as much as will //fit is copied Friend ostream& operator << (ostream& outs, const StringVar& the_string); //Overload << operator so it can be used to output values StringVar //Precondiction: If outs is file, outs must be connected to file private: char*value; //pointer to dynamic array that holds the string value int max_length; //declared max length of any string value }; <Definitions of member functions and oerloaded operators goes here> void conversation(int max_name_size) { using namespace std; StringVar your_name(max_name_size), our_name(Borg); cout << What is your name?\n; your_name.input_line(cin); cout << We are << our_name << endl; cout << We will meet again << your_name << endl; }

int main { using namespace std; conversation(30); //Memory is returned to freestore when function end cout << End of conversation.\n; return 0; }

Destructors
Dynamic variables do not go away unless program makes suitable call to delete. Destructor is member function called automatically when object of class passes out of scope.If program contains local variable that is an object with a destructor, then when function call end, destructor is automatically called. Destructor calls delete to eliminate all dynamic variables created by object. Member function ~StringVar is destructor for class StringVar. Like constructor, destructor has the tilde simbol ~ at beginning of name. Destructor has no parameters.

Chapter 8: Strings and Vectors


C-String variable array of characters char Array_Name[Max_C_String_Size + 1]; Example: char my_c_string[11]; The +1 allow for null character \0 which terminating C string stored in array Example can hold ten or fewer characters. Can initialize C-string when declaring: char my_c_string[20] = Hi there.; Can omit the array size char short_string[] = abc; is equal to char short_string[4] = abc; Is not the same as char short_string[] = {a, b, c}; Char \0 is not put in this array as before!! char our_string[5] = Hi; int index = 0; while (our_string[index] != \0) { our_string[index] = x; index++; } Need to track \0 and must not destroy when changing values in the array. As safe feature ensure index is smaller than array size int index = 0; while ((our_string[index] != \0) && (index < SIZE)) { our_string[index] = x; index++; } Cannot copy strings with = sign. Need to use strcpy(a_string, Hello); This does not include \0 and alternative can use strncpy(b_string, a_string, 9); //leaving room for \0 Cannot use == to compare two strings. Need to use if (strcmp(c_string1, c_string2)) cout << Strings are not the same; else cout << strings are the same; //Not comparison is TRUE if strings to not match!! If at any point the numeric encoding of char in string1 is less than numeric character in string2, testing stop and negative number is returned. If char is greater then positive number is returned. If strings are the same, 0 is returned. If using strcmp in boolean if expression, non zero value will be converted to true and zero converted to false. Functions strcpy and strcmp are in library <cstring>, so need to use #using <cstring>;

Predefined C-String Functions in <cstring> strcpy(target_string, src_string) Copy C-string src_string into target_string {doe not check target_string is large enough to hold value} strncpy(target_strgin, src_string, Limit) copy strings at most limit strcat(target_string, src_string) concatenate src_string at end of target_String {does not check if target_string is large enough} strncat(target_string, src_string, limit) concatenate string and limit characters are appended strlen(src_string) return integer equal to length of src_string, \0 is not counted. strcmp(String_1, String_2) return 0 (convert to false) if same, < 0 if 1 < 2, > 0 if 1 > 2 (convert to true). strncmp(String_1, String_2, Limit) at most limit char compared As with array, when function change value of C-string, need to include int parameter giving declared size of C-string variable. If only use value in C-string and not change value, no need for int since \0 can be used to detect end of C-string. C-String Input and Output: C strings output using << operator cout << news << Wow\n; C string input using >> operator, but this would skipp all white spaces like blanks, tabs and line breaks. char a[80], b[80]; cout << Enter input:\n; cin >> a >> b; cout << a << b << END of INPUT\n; Result: Enter input: Do be do to you! DobeEND of INPUT Do stored in a, be stored in b To read entire string line char a[80]; cout << Enter input:\n; cin.getline(a,80); cout << a << END of INPUT\n; Result: Enter input: Do be do to you! Do be do to you!END of INPUT Reading end when line ends, even if resulting C string is shorter than maximum. char a[5]; cout << Enter input:\n; cin.getline(a,5); cout << a << END of INPUT\n; Result: Enter input: Dobedowap DobeEND of INPUT Four characters (not five) are read. Work same for input and output for files.

C-String to Number Conversions and Robust input: C string 1234 is not same as number 1234. atoi function takes C string and return int value. int x = atoi(657); //set x to 657 double y = atof(12.37); //set y to 12.37 Program using atoi and atof must contain directive: #include <cstdlib> If argument not correspond to int, will return 0. atoi(#37); //return 0 If number too large for int, can convert to long long x = atol(234235235234);

VECTORS Is an array that can grow (and shrink) in length while program is running. Array length cannot be changed. Vector same as array, but length can be changed while program is running. Declare variable v for vector with base type int: vector<int> v; Notation vector<Base_Type> is a template class, can plug in any type for Base_Type and will produce a class for vectors with that base type. Vector elements are indexed starting from 0. v[i] = 42; cout << Number is << v[i]; Restriction with square bracket notation with vectors. Cannot initialize the ith element using v[i]; can only change element alaready giving value. To add element to index of vector for first time, use member function push_back. Add elements to vector in order of positions, first at 0,then 1, 2 ... Member function push_back adds element in next available position. vector<double> sample; sample.push_back(0.0); sample.push_back(1.1); sample.push_back(2.2); Number of elements in vector is called size of vector. Function member size can be used to determine how many elements are in vector. sample.size(); //return 3 from above push_back functions Can write all elements in vector: for (int i = 0; i < sample.size(); i++); cout << sample[i] << endl; Note function size return unsigned integer (only nonnegative integers) Automatic conversion done to type int, but could cause errors for (unsigned int i = 0; i < sample.size(); i++); cout << sample[i] << endl; Vector constructor to take integer argument and will initialize number of positions given as the argument. vector<int> v(10); First 10 elements initialized to 0 and v.size() return 10. Can then set value of ith element using v[i] for values of I equal to 0 to 9. for (unsigned int i = 0; i < 10; i++) v[i] = i; To set ith element greater then 10, use push_back. Need to use library vector #include <vector> Using namespace std;

At any point vector has capacity, number of elements for which memory is allocated. The size is member elements, capacity is number of elements for which memory is allocated. Capacity is larger as size, and always greater or equal to size. Can ignore capacity of vector. Efficiency issue might want to manage capacity and not accept default behavior of doubling capacity whenever more is needed. Can use member function reserve to explicitly increase capacity of vector. v.reserve(32); set capacity to 32 elements and v.reserve(v.size() + 10); increase with 10 more than number of current elements in vector, but can not decrease capacity of vector of argument is smaller then current capacity. Can change size of vector using member function resize. v.resize(24); If previous size was less than 24, new elements are initialized as described to constructor with integer argument. If previous size was greter thn 24, all but the first 24 elements are lost. Capacity automatically increase if need be. Using resize and reserve can shrink size and capacity of vector when no longer need for some elements or some capacity. 8.4 Converting between string objects and C strings This section explains how to convert a string object to a C string by using the string member function c_str(). In section 6.6 on page 11 of this Study Guide, we use the c_str() function to convert an external file name in string format to a C string, which is the format required by the stream member function open(). 8.5 The class vector The class vector is defined in the Standard Template Library (STL) for C++. The STL vector container is a generalization of array. A vector is a container that is able to grow (and shrink) during program execution. A container is an object that can contain other objects. The STL vector container is implemented using a template class (templates are covered in Chapter 17). A vector named v that can contain int values is declared with vector<int> v; In order to use it, we need to include the correct header file that contains the declarations of the vector class and to make the names from the standard namespace available with: #include <vector> using namespace std; A vector is a fixed-length group of elements of uniform type, indexed by integer keys. As mentioned before, vectors can be considered to be a generalization of the built in C++ array type. However, they have several other notable 98 features not associated with the basic array. The main advantages of using vectors is that the size of a vector need not be fixed and can be changed during program execution, which is not possible with an array. Vectors are also important when the ability to rapidly access arbitrary elements is necessary, because, as with an array, individual elements in a vector can be directly indexed. The elements in a vector are assumed to be unsequenced, but the operation sort in the STL can be used to place the elements of a vector in order. 8.6 The Standard Template Library (STL) The Standard Template Library (STL) standardises commonly used components through a set of containers (lists, vectors, sets, maps, etc.) that hold objects, built-in objects and class objects. The containers keep the objects secure and define a standard interface through which they can be manipulated. The STL also contains standard algorithms that can be applied to the objects while they are in the container, for instance, to sort them, compare them, merge objects into another container, find a specific object and many more operations. The STL algorithms use iterators, which are similar to pointers, to operate on the objects in the containers. The algorithms manipulate the objects in a standard way and the iterators ensure that the algorithms handle all and only the elements in the containers, and no more. You do not need to be able to use the iterator access methods for vectors.

Chapter 14: Recursion

Recursion mean allowing a function or procedure to call itself. It keeps calling itself until some limit is reached. A function definition may contain a call to the function being defined. In such case the function is called recursive. Successful definition of recursive function always include at leat one case that does not involve recursive call, as well as one or more cases that do involve at least on recursive call. Example: #include <iostream> using namespace std; void write_vertical(int n) { if (n < 10) { cout << n << endl; } else //n is two or more digits long { write_vertical(n / 10); cout << (n % 10) << endl; } } int main() { cout << write_vertical(3): << endl; write_vertical(3); cout << write_vertical(12): << endl; write_vertical(12); cout << write_vertical(123): << endl; write_vertical(123); return 0; } Recursive Function for Values: Recursive not limited to void functions. Can return a value of any type. Successful recursive function definition that return value is: - One or more case in which value returned is computed in terms of call to same function. - One or more case in which value return is computed without use of recursive call (base case or stopping case) Example: #include <iostream> #include <cstdlib> using namespace std; int power(int x, int n); { if (n < 0) { cout << Illegal argument to power.\n; exit(1); } if (n > 0)

return (power(x, n 1) * x); else //n == 0 { return (1); } } int main () { for (int n = 0; n < 4; n++) cout << 3 to the power << n << is << power(3, n) << endl; return 0; } 14.4 Recursion The summation function, designated by an uppercase (Sigma) in mathematics, is a popular example of recursion:

or, put in a different way: sum(n) = 1 if n = 1 = sum(n-1) + n if n > 1 Written as a recursive function, this gives: int calc_sum (int num) { int sum; if (num == 1) //base case sum = 1; else sum = calc_sum(num-1) + num; //recursive call return sum }; Suppose you call calc_sum for 3: int answer = calc_sum(3); calc_sum (3) calc_sum (2) + 3 calc_sum (2) calc_sum (1) + 2 At 1, the recursion stops and becomes 1. calc_sum (3) 3 + 3 = 6

answer 6 Recursion works backward until a given point is reached at which an answer is defined (the base case), and then works forward with that definition, solving the other definitions which rely upon that one. All recursive procedures/functions should have some sort of test to stop the recursion. Under one condition, called the base condition, the recursion should stop. Under all other conditions, the recursion should go deeper. In the example above, the base condition is if (num == 1). If you dont build in a base condition, the recursion will either not take place at all, or become infinite.

Chapter 15: Inheritance

. .

. semoceb semoceb semoceb

calc_sum (2)

1 + 2 = 3

. .

semoceb semoceb

n + i = i
1=i 1=i

1-n

Inheritance is the ability to define new classes from existing classes. The new classes that we create from the existing classes are called derived classes; the existing classes are called the base classes. The derived classes inherit the properties of the base classes. So rather than create completely new classes from scratch, we take advantage of inheritance and reduce software complexity. Use inheritance to derive one class from another. New class known as derived class, created from another class called the base class. A derived class automatically has all the members of that base class, and can have additional member functions and/or additional member variables. Example: ifstream is derived from predefined class istream by adding functions such as open and close. The stream cin belong to class of all input streams (the class istream), but does not belong to class input-file stream (does not belong to ifstream), lack member function open and close of the derived class ifstream. Example: Design employee record keeping class for salaried and hourly paid employees. //Header file employee.h //Interface for class Employee //Used as base class to derive classes for different kinds of employees #ifndef EMPLOYEE_H #define EMPLOYEE_H #include <string> using namespace std; namespace employeessavitch { class Employee { public: Employee(); Employee(string the_name, string the_ssn); string get_name() const; string get_ssn() const; double get_net_pay() const; void set_name(string new_name); void set_ssn(stinrg new_ssn); void set_net_pay(double new_net_pay); void print_check() const; private: string name; string ssn; double net_pay; }; } //employeessavitch #endif //EMPLOYEE_H

//This is the file: employee.cpp

//This is the implementation for the class Employee //This interface for the class Employee is in the header file employee.h #include <string> #include <cstdlib> #include <iostream> #include emplayee.h using namespace std; namespace employeessavitech { Employee::Employee():name(No name yet), ssn(No ssn yet), net_pay(0) { //left empty } Employee::Employee(string the_name, string the_number) :name(the_name), ssn(the_number), net_pay(0); { //left empty } string Employee::get_name() const { return name; } string Employee::get_ssn() const { Return ssn; } double Employee::get_net_pay() const { return net_pay; } void Employee::set_name(string new_name) { name=new_name; } void Employee::set_ssn(string new_ssn) { ssn=new_ssn; } void Employee::set_net_pay(doubl new_net_pay) { Net_pay=new_net_pay; } void Employee::print_check() const { cout << \nERROR: print_check FUNCTION CALLED FOR AN \m; << UNDEFINED EMPLOYEE. Aborting the program.\n; << Check with the author of the program about this bug.\n;

exit(1); } }//employeessevitch

//This is the header file hourlyemployee.h //This is the interface for the class HourlyEmployee. #ifndef HOURLYEMPLOYEE_H #define HOURLYEMPLOYEE_H #include <string> #include employee.h using namespace std; namespace employeessavitch { class HourlyEmployee : public Employee { public: HourlyEmployee(); HourlyEmployee(string the_name, string the_ssn, double the_wage_rate, double the_hours); void set_rate(double new_wage_rate); double get_rate() const; void set_hours(double hours_worked); double get_hours() const; void print_check(); //only list declaration of inherited member function if //want to change definition of function private: double wage_rate; double hours; }; }//employeessavitch #endif //HOURLYEMPLOYEE_H

//This is the header file salariedemployee.h //This is the interface for class SalariedEmployeed. #ifndef SALARIEDEMPLOYEE_H #define SALARIEDEMPLOYEE_H #include <string> #include employee.h using namespace std; namespace employeessavitch { class SalariedEmployee : public Employee { public: SalariedEmployee(); SalariedEmployee(string the_name, string the_ssn,

double the_weekly_salary); double get_salary() const; void set_salary(double new_salary); void print_check(); private: double salary;//weekly }; }//employeessavitch #endif //SALARIEDEMPLOYEE_H Note definition of derived class begin as other class definition but add colon, the reserved word public, and the name of base class to the first line of class definition: class HourlyEmployee : public Employee { The derived class HourlyEmployee automatically receive all the member variables and member functions of the base class Employee and can add additional member varialbes and member functions. Definition of class HourlyEmployee does not mention member variables name, ssn and net_pay, but every object of class HourlyEmployee has member variables named name, ssn and net_pay. The member variables name, ssn, and net_pay are inherited from the class Employee. The class HourlyEmployee declares two additional member variables names wage_rate and hours. Every object of class HourlyEmployee has five member variables names name, ssn, net_pay, wage_rate and hours. Note definition of derived class HourlyEmployee only list added member variables. Member variables defined in base class are not mentioned. They are provided automatically to the derived class. In the implementation file for dericed class, like implementation of HourlyEmployee, give the definitions of all added member functions. Note do not give definitions for inherited member functions unless definition of member function os changed in derived class. Definition of inherited member function can be changed in definition of derived class so it has meaning in derived class that is different from what it is in the base class. Called redefining inherited member function. Example is print_check() is redefined in definition of derived class HourlyEmployee. To redefine member function definition, list in class definition and give new definition, as would do with member function that is added in derived class. //This is the file: hourlyemployee.cpp //This is the implementation for the class HourlyEmployee //The interface for class HourlyEmployee is in the header file hourlyemployee.h #include <string> #include <iostream> #include hourlyemployee.h using namespace std; namespace employeessavitch { HourlyEmployee::HourlyEmployee() : Employee(), wage_rate(0),hours(0) { //left empty }

HourlyEmployee::HourlyEmployee(string the_name, string the_number, double the_wage_rate, double the_hours) : Employee(the_name, the_number), wage_rate(the_wage_rate), hours(the_hours) { //empty } void HourlyEMployee::set_rate(double new_wage_rate) { wage_rate = new_wage_rate; } double HourlyEmployee::get_rate() const { return wage_rate; } void HourlyEmployee::set_hours(double hours_worked) { hours = hours_worked; } double HourlyEmployee::get_hours() const { return hours; } void Hourlyemployee::print_check() { set_net_pay(hours * wage_rate); cout << \n----------------------------------------------\n; cout << Pay to the order of << get_name() << endl; cout << The sum of << get_net_pay() << Dollars\n; cout << \n----------------------------------------------\n; cout << Check Stub: NOT NEGOTIABLE\n; cout << Employee Number: << get_ssn () << endl; cout << Hourly Employee. \nHours worked: << hours << Rate: << wage_rate << Pay: << get_net_pay() << endl; cout << \n----------------------------------------------\n; } Note base class is also called parent class and derived class called child class. Constructors in Derived Class Constructor in base class is not inherited in derived class, invoke constructor of base class within definition of derived class constructor. Constructor for derived class use constructor from base class in special way. Constructor for base class initializes all data inherited from base class. Constructor for derived class begin with invocatioin of constructor for base class. Special syntax for invoking base class constructor illustrated by constructor definitions for class HourlyEmployee: 15.2 Learning Objectives

After having worked through section 15.1 you should be able to: - distinguish between is-a relationships and has-a relationships; - understand the role of public inheritance in class design; - create new classes by inheriting from existing classes; - understand how inheritance promotes software reusability; - understand the notions of base classes and derived classes; - understand the effect of the access-specifier labels (i.e private, public and protected) in terms of public inheritance. - define constructors for a derived class; - redefine member functions; - demonstrate that you understand the difference between redefining a member function in a derived class and overloading a member function. 15.3 Inheritance 15.3.1 The Purpose of Inheritance The primary purpose of inheritance is to reuse code by exploiting the is-a relationship between objects. Software reusability saves time in program development. It encourages the reuse of proven and debugged high-quality software, thus reducing problems after a system becomes functional. Significant overlap between two classes indicates a potential case for inheritance. In the real world, objects exist in relation to one another. In solving problems we need to be as close to the problem as we can, within abstraction that allows us to ignore details in order to solve our problem. In our problem, we may describe one object as being like another, even saying one object is-a type of some other object. In an example of is-a relationships, we might think of a class of (general) vehicles, and then think of a kind of vehicle for carrying passenger (automobiles), another kind that is small and carries cargo in the open (pickup truck), still another that carries cargo in an enclosure (van), others yet that carry cargo enclosed and are articulated - tractortrailer). The Truck, Van, and Car classes inherit their common features from the class Vehicle. In these cases, a car is a vehicle, so are pickups, vans, and tractor-trailers. A car is a vehicle; a pickup truck is a vehicle, and so on. The class abstraction of vehicle is the base class and the vehicles that bear the is a relation to the base class are derived classes. In this example, the base class contains the features common to all types of vehicles. The derived class inherits all those common features and adds its own, extra, additional features to the base class to form its distinctiveness. In this way, the common features (commonalities) are encapsulated in the base class, and the distinctions are encapsulated in the derived class. The commonality is passed from the base class to the derived class with inheritance. A derived class is therefore more specific than its base class. This relationship is known as the isa relationship. The is-a relationship specifies that one abstraction is a specialization of another. If we write this example in C++, we have class Vehicle {/* . . . */}; class Car : public Vehicle { /* . . . */}; class Truck : public Vehicle { /* . . . */}; class TractorTrailer: public Truck {/* . . . */}; class StationWagon : public Car {/* . . . */ }; We see that inheritance creates a new class, called the derived class, that is an extension, specialization or modification of one or more existing classes, called the base classes. In the situation where there is only one base class, we have single inheritance. Where there is more than one base class, multiple inheritance occurs. In this, example, we could illustrate multiple inheritance by defining class Emergency {/* . . . */}; and have had a class PoliceCar inherit from both class Car and class Emergency. Or we could have a class Ambulance inherit from both class Truck and class Emergency. The PoliceCar and Ambulance would inherit features from Car and the derived class adds its distinguishing features. Since multiple inheritance is beyond the scope of this module, we will not discuss it further. Notice that the is-a relationship is transitive (that is, a TractorTrailer is a Truck, a Truck is a Vehicle, and therefore a TractorTrailer is a Vehicle), but it is not reflexive (that is, not all Vehicles are TractorTrailers). Another way of
p i h s
n

expressing the is-a relationship is to say that a TractorTrailer is a kind of Truck and that an Truck is a kind of Vehicle. See also text box on page 867 in Savitch. In addition to the is-a relationship that represents inheritance, two other relationships between abstractions are 118 commonly used on object-oriented design, namely the has-a and usesa relationships. The has-a relationship says that some object is part of another. The has-a relationship implies containment. For example, a car has an engine. The uses-a relationship says that one object uses another object in some way. This usually realized by one object communicating with another via member functions. For example, suppose the operating system has a clock object that maintains the current date and time. The clock object has member functions that return the current date and time. Other objects that need the date or time, use the clock object by calling the appropriate member functions to fetch the current date or time. Public inheritance should be used when a new class (the derived class) describes some set of objects that is a subset of the objects being described by the base class. This relationship is known as the is-a relationship. So what does public inheritance mean? Consider the classes Base and Derived: class Base { public: int x; protected: int y; private: int z; }; class Derived : public Base { public: int total( ) const { int sum = x; sum += y; //sum += z; //cannot access z directly sum += q; return sum; } private: int q; }; Public members of the Base class are public members of the Derived class too. The Derived class inherits all data members and all member functions from the Base class, but it can access only those that are not private. That is, a derived class can access public and protected members of its base class. In the example, class Derived can access x and y directly but not z, because z is private in class Base. If we want to access z which is a private data member in the Base class, then we can access z in one of two ways: (1) by creating a public / protected accessor in class Base, such as int get_z( ) const { return z; } (2) or we could make z protected (more about this on page 870 in Savitch). Now consider the following client program that instantiates objects of type Base and Derived: int main( ) { Base b; Derived d; cout << b.x; cout << d.x; //cout << b.y; //cout << d.y; //cout << b.z; //cout << d.z;
e
c n a t

} Since x is public in class Base, it is also public in class Derived through public inheritance. Therefore we can access x in the client program. But we cannot access y because it is a protected member of both Base and Derived. And of course we cannot access z because it is private. Note, that the access specifier for class inheritance defaults to private. If class Derived has base class class Base {/* . . .*/}; class Derived : access-specifier Base { /* . . . */}; //where access-specifier is one of public, protected, private then the access that is granted to member functions of class Derived depends on the access-specifier selected. If the access-specifier is omitted, access to all members of the base class automatically defaults to private. This would mean that Derived has no access to the member functions and data members of Base.

Chapter 17: Templates


Note following function swap_values applies only to type int. void swap_values(int & variable1, int & variable2) { int temp; temp = variable1; variable1 = variable2;

Base

variable2 = temp; } IF want to use different variable type (like char), need to overload functioin using char type. void swap_values(char & variable1, char & variable2) { char temp; temp = variable1; variable1 = variable2; variable2 = temp; } Templates for Functions Possible to use one function for different variable types. Definition and function declaration begin with: template<class T> Called template prefix, tell compiler definition or function declaration to follow is a template and T is type parameter. In this context class means type. //Interchange values of variable1 and variable2 Template<class T> Void swap_values(T& variable1, T& variable2) { T temp; temp = variable1; variable1 = variable2; variable2 = temp; } Templates for Data Abstracts: Syntax for class templates is same as for function templates. Following placed before template definition: template<class T> Type parameter T used in class definition. Example: //Class for a pair of values of type T: template<class T> class Pair { public: Pair(); Pair(T first_value, T second_value); Void set_element(int possition, T value); //Precondition: position is 1 ot 2. //Postconditioin: //Position indicated has been set to value T get_element(int position) const; //Preconditioin: position is 1 or 2. //Return the value in position indicated private: T first; T second; }; Once class template defined, can declare objects of this class. The declaration must specify what type is to be filled in for T.

Following declare object score so can record pair of integers and declares object seats to record pair of characters: Pair<int> score; Pair<char> seats; Object are used just like any other object. Following set score to 3 for first team and 0 for second team: score.set_element(1, 3); score.set_element(2, 0); The member functions for class template are defined same way as member functions for ordinary classes. Only difference is memver function definitions are themselves templates. Following are appropriate definitions for member functions set_element and for constructor with two arguments: //Uses iostream and cstdlib: template<class T> void Pair<T>::set_element(int position, T value) { if (position == 1) first = value; else if (position == 2) second = value; else { cout << Error: Illegal pair position.\n; exit(1); } } template<class T> pair<T>::Pair(T first_value, T second_value) : first(first_value), second(second_value) { //empty } Notice class name before scope resolution operation is Pair<Y>, not Pair. Name of class template may be used as type for function parameter. Following is possible declaratioin for function with parameter for pair of integers: int add_up(const Pair<int>& the_pair); //Return sum of two integers in the_pair Note specified the type, in this case int, to be filled in for parameter T. Can also use class template within function template. Example, rather than defining specialized function add_up given above, could define functioni template as follow so function applies to all kinds of numbers: template<class T> T add_up(const Pair<T>& the_pair); //Precondition: Operator + is defined for values of type T. //Returns sum of two values in the_pair. Assert: Tool to ensure expected conditions are true at the location of the assert statement. If condition not true, an error message and program abort occur. Need to use #include <cassert> in order to use. #include <iostream> #include <cassert>

using namespace std; int arith( int term ) { int first = 1; int diff = 3; assert (term != 0); if (term == 1) return ( 1); else return (((term-first) * 3) + 1); } int main() { int term, answer; cout << "Please key in the number of the term : "<< endl; cin >> term ; answer = arith(term); cout << "the value of term " << term << " is " << answer << endl; return 0; }