Download
46 699 object oriented programming www andrew cmu edu course 46 699 n.
Skip this Video
Loading SlideShow in 5 Seconds..
46-699 Object-oriented Programming andrew.cmu/course/46-699/ PowerPoint Presentation
Download Presentation
46-699 Object-oriented Programming andrew.cmu/course/46-699/

46-699 Object-oriented Programming andrew.cmu/course/46-699/

143 Vues Download Presentation
Télécharger la présentation

46-699 Object-oriented Programming andrew.cmu/course/46-699/

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. 46-699 Object-oriented Programmingwww.andrew.cmu.edu/course/46-699/ Ananda Guna May 17, 1999 - Lecture #1 guna@ cs.cmu.edu School of Computer Science Carnegie Mellon University

  2. Administrivia • Web page, schedule, text • TA’s: Ramu Arunachalam(Pgh) and TBA (NYC) • Due dates • Final exam • Recitation hours • Software • MSVC++ (5.0) • Metrowerks Codewarrior • Any other compiler e.g. Borland • g++

  3. C++: Language Background • Designed “on top of” C • C plus OOP features, hence the name C++ • Implications • Almost all of the C features still work • Some features were simplified, notably the I/O • Many people claim to program in C++, but never really use its OOP features - also called “a better C” • Most compilers support C/C++ • The challenge of learning C++ is in the paradigm shift • Java is based on C++

  4. Review • Variables • Data types • Primitives: int, double, float, char... • Conditionals (if, if-else, switch) • Repetition (for, while loops) • General structure of a C program • Functions • Prototypes • Arguments/parameters • Call by value

  5. Review • All variables must be declared before use • Must specify the type of your variable • Compiler allocates memory • e.g. int count=0; float num1= 0.0, num2 = 0.0; • Always initialize your variables or they contain garbage • Conditionals: Used to control execution • if • if-else, nested if • switch

  6. 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; }

  7. 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 while{ //loop body statements; // Be sure to update loop control variable } while (i < MAX);

  8. 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)

  9. 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 varibles. Why? • Global constants are fine. Why? • E.g. const int MAX = 10; // same as #define in C

  10. 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

  11. Call by value example void print ( int x, float y){ cout << x << “ “ << y << endl; } int main(){ 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

  12. Call by reference example void swap ( int& a, int& b){ // the addresses are passed int temp; temp = a; a = b; // change a ==> change x b = temp; // change b ==> change y cout << a << “ “ << b << endl; } int main(){ int x = 7; int y= 55; swap(x, y); // Note: NO & is required here unlike C cout << x << “ “ << y << endl; return 0; } x y 7 55

  13. Arrays • Group/collection of memory cells • Each cell must be of the same type • Declaring an array in C++: • const int MAX = 30; // #define in C • 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

  14. Passing arrays as arguments void multArray(float arr[], int count){ // no & for array arguments - as in C int i; for ( i = 0; i < count; i++){ arr[i] *= 10.2; // change to the original array } return sum; } //multArray // 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>

  15. const array arguments void multArray(const float arr[], int count){ // no & for array arguments - as in C int i; for ( i = 0; i < count; i++){ arr[i] *= 10.2; // change to the original array } } //multArray • 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

  16. 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) • Much simpler and cleaner than C! • Sample program

  17. 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 • Much simpler and cleaner than C!

  18. File I/O in C++ ctd... • ifstream infile(“infile.txt”); is ok too • ofstream outfile(“outfile.out”) is ok too • In each case object constructor is called • logical file physical file • 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>>…}

  19. File I/O in C++ ctd... • You may use #include “Openfile.h” utility • ifstream infile; • OpenFileForReading(“Enter input file “ , infile); • ofstream outfile; • OpenFileForWriting(“Outfile ? “ , outfile); • infile.close(); • outfile.close(); // explicit close • File stream is also destroyed upon leaving the scope.

  20. Problem Solving Process • Review: • Algorithm • Top-down design, stepwise refinement • Pseudocode • Flow Chart • Phases of software development • Planning: figuring out the problem specs • Design: the algorithm, use pseudocode etc • Code: Translate the design into C++/Java syntax • Code review: “Spell-check” your code. Simulate the compiler looking for syntax errors • Compile: With a thorough code review, compile time is small • Test/debug

  21. System Costs: Hardware vs. Software* 100% Software PercentSystemCost Hardware 1950 2000 Year * courtesy R.Pattis

  22. Motivation for Design before Coding • Analogy: Think about how you write a paper • Problem Statement? Outline? Abstract? Fill in details based on the outline? Refine sections/paragraphs? How do you proof your paper? Do you just type something and watch the spell-checker or do you print it out and read it for errors? • Your solution is only as good as your design • Coding should be low priority compared to design • If you take short cuts, you will end up spending a lot more time on the program. • Bottom Line: There is nothing mysterious about coding!!!

  23. 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

  24. Problem Solving - OO Design • Identify the objects • Identify the operations • Design the algorithm/decompose into smaller chunks • E.g: Compute the amount of tuition to be paid • Name the objects • # credit hours • cost per credit hour • Other costs, such as student activity fee etc • Any discounts • Name the operations to be performed: • Addition, subtraction, multiplication • Algorithm

  25. 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

  26. 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

  27. OOP Terminology • Program = objects cooperating to solve a problem • Properties of an object: • State ==> data ==> nouns • Operations ==> behavior ==> verbs • Identity

  28. Object Examples • Example 1: An electronic mailbox • States: full or empty • Operations: add, delete ... • Identity: any 2 mailboxes will be different e.g. hou and aj29 each have a mail box • Example 2: traffic signal

  29. Object Components • An object is composed of both data and Operations which can act upon the data Operations Data • In a C++ object: • Operations ==> member functions (methods) • Data ==> data members

  30. 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 : checkingaccount • Objects: minnieCheckacct, mickeyCheckacct

  31. Example: OOP Design • Problem: write a program to simulate an ATM • Data (nouns): • Account name • Account balance • ... • Operations /behavior(verbs): • Deposit • Withdraw • Inquire balance • ...

  32. Problem ( Elevator Control Problem) Simulation of an elevator control system. 20 floors , 4 elevators 1. Identify the data objects 2. Identify the data operations 3. Solve the problem • Read Chapter 6-7 (Dietel Text) • Any questions Email : guna@cs.cmu.edu