200 likes | 222 Views
15-112 Object Based Programming. Victor Adamchik Spring 2001 www.cs.cmu.edu/~adamchik/15-112. adamchik@ cs.cmu.edu. Review. Variables Data types Conditionals (if, if-else, switch) Repetition (for, while loops) Functions. Scope of a variable.
E N D
15-112 Object Based Programming Victor Adamchik Spring 2001 www.cs.cmu.edu/~adamchik/15-112 adamchik@ cs.cmu.edu
Review • Variables • Data types • Conditionals (if, if-else, switch) • Repetition (for, while loops) • Functions
Scope of a variable • The segment of the program where it can be “seen” • A local variable’s scope is the block within which it is declared plus any nested blocks • A global variable’s scope is the entire program • Lifetime of variables: • Locals die upon exit of a function • Globals are “alive” throughout the “life” of the program • It is bad style to use global variables. Why? • Global constants are fine. Why? • E.g. const int MAX = 10; // same as #define in C
Conditionals • if (boolean condition true){ if (boolean condition true){ statements; if (boolean condition true){ } ... } } • if (boolean condition true){ if (boolean condition true){ statements; statement } else { } else if (boolean condition true){ statements; statements; } } else if (...) • switch(varName){ //int varName case 1: statements; break; // REQUIRED case 2,3,4: statements; break; // REQUIRED default: debug statement; }
Repetition • Loops • for: Used when we know the # iterations • while: We don’t know the exact # iterations, but we know the exit condition • do-while: Executes the loop body at least once, test is at the bottom • for ( i=0; i< MAX; i++){ //loop body statements; } • while (i < MAX){ // assume i is initialized //loop body statements; //Be sure to update loop control variable } • do { //loop body statements; // Be sure to update loop control variable } while (i < MAX);
Functions • Units or modules within a program • Each performs a specific task • Allow for cleaner programs, promote reuse. • May be • system-defined. E.g. the math library functions • User defined tailored to the application • Must be called or invoked to be executed • Prototypes are optional if the function implementations appear before the function call. However, it is good style to use function prototypes • Can pass arguments to each other • Can return a value upon exit(Single return functions)
Passing Arguments/parameters • Call by value: • A copy of the variable is passed • Call by reference: • The address of the variable is passed • The called function has direct access to the variable • Arguments • Must match in number • Must match in type • The names do not matter, what matters is the order of the arguments, i.e. the first is mapped to the first and so on
Call by value example void print (int x, float y) { cout << x << “ “ << y << endl; } int main(void) { int x = 10; float y = 22.7; print(x, y); return 0; } // What will be the output for print(y,x)? 10 22.7 10 22.7
Call by reference example void swap (int& a, int& b) { // the addresses are passed int temp = a; a = b; // change a ==> change x b = temp; // change b ==> change y cout << a << “ “ << b << endl; } int main(void) { int x = 7, y= 55; swap(x, y); // Note: NO & is required here unlike C cout << x << “ “ << y << endl; return 0; } x y 7 55
Arrays • Group/collection of memory cells • Each cell must be of the same type • Declaring an array in C++: • const int MAX = 30; • float stocksPrices[MAX]; 51.5 98.30 [0] [1] [MAX - 1] - Subscript/index begins at zero - stocksPrices[0] is the first element - Every element is of type float
Passing arrays as arguments void multArray(float arr[], int count){ // no & for array arguments for (int i = 0; i < count; i++) arr[i] *= 10.2; return sum; } // function call multArray(arr, count); // assume arr has been loaded // count is the # items in the array cout << "\narr[0] ” << setiosflags(ios :: fixed|ios ::showpoint) << setw(10) << setprecision(2)<< arr[0]; //output with two decimal places // need #include <iomanip>
const array arguments void multArray(const float arr[], int count) { for (int i = 0; i < count; i++) arr[i] *= 10.2; } • const means the function can use, but may not change the array • The above will throw a compile error - at which line? • Use const to protect against accidently changing the array values • Printing the contents of an array • Using the array to do some computation
Input/output in C++ • To read from the console: cin • cin >> varName; // read into this variable • cin >> varName1 >> varName2; • >> is called the stream extraction operator • To print to the console • cout << varName; // dump contents of varName • cout << varName1 << varName2 << endl; • cout << varName1 + varName2 << “\n”; • << is called the stream insertion operator • endl: end of line (newline plus flush the output buffer)
File I/O in C++ • Sequential Access Files - input • programmer must create/recognize structure • ifstream infile(filename, ios::in) • if (!infile) { cerr<<“File cannot be open”; • exit(1);} • infile >> date >> maxprice >> minprice >> close; • File output • ofstream outfile(filename, ios::out) • outfile << varName1 << varName2 << endl; • if no file then a file is created • << is called the stream insertion operator • >> is called the stream extraction operator
File I/O in C++ ctd... • ifstream infile(“infile.txt”); is ok too • ofstream outfile(“outfile.out”) is ok too • alternative style • ofstream outfile; • outfile.open(“filename”,ios::out); • Reading a file of data to eof • while (infile>>var1>>var2…) { process} • while (!infile.eof()) { infile>>var1>>var2>>…}
OOP Versus Non-OOP • Procedural programmingOOP - Identify tasks/sub-tasks - Design the classes - Write procedures - Design the methods - Procedures act upon data - Objects communicate to solve to solve the problem the problem - Start with “verbs” - Start with “nouns” - Data is secondary - Data is primary
Key Elements of OOP • Abstraction: Focus on the important, ignore the details • e.g. Driving a car • The interface of the car is what the driver sees on the outside, i.e. the dash board, the gas pedal and so on. • The implementation is a detail, e.g. what exactly happens when I step on the gas pedal. • Encapsulation: Information hiding • The details of an object are hidden. • Users are not allowed to make changes to the implementation. • If there is any change in the implementation, it does not affect the users(clients) of the interface. • E.g. A Stack Class has as its interface: init, push, pop. The implementation may be changed from an array to a linked list
Key Elements of OOP • Inheritance • Building upon what is already defined • A class can inherit from another class much like a child inherits from its parent • Polymorphism • Greek for “many shapes” • Same name for different things • Two forms in OOP • Overloading: Functions with the same name • Over-riding: A child class redefining its parent’s functions
Classes • Class: • A collection of related objects. • Instance of a class = object • Factory with blueprints/instructions to build gadgets • Objects: the gadgets the factory makes. • Example: • Class : checking account • Objects: minnieCheckacct, mickeyCheckacct
Example: OOP Design • Problem: write a program to simulate an ATM • Data: • Account name • Account balance • ... • Operations /behavior: • Deposit • Withdraw • Inquire balance • ...