• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Oop lec 2(introduction to object oriented technology)
 

Oop lec 2(introduction to object oriented technology)

on

  • 250 views

 

Statistics

Views

Total Views
250
Views on SlideShare
250
Embed Views
0

Actions

Likes
0
Downloads
26
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Oop lec 2(introduction to object oriented technology) Oop lec 2(introduction to object oriented technology) Presentation Transcript

    • Introduction to Object Technology, Introduction to C++ Programming Lecture No 2 COMSATS Institute of Information & Technology
    • Reference Books: Object Oriented Programming in C++, Robert Lafore C++ How to Program, Deitel & Deitel Object oriented programming, Ashok N. Kamthane 2 COMSATS Institute of Information Technology Object Oriented Programming
    • High-level Languages Common programming languages include … C C++ Java Pascal Visual Basic FORTRAN COBOL Lisp Scheme Ada These high – level languages Resemble human languages Are designed to be easy to read and write Use more complicated instructions than the CPU can follow Must be translated to zeros and ones for the CPU to execute a program 3 COMSATS Institute of Information Technology Object Oriented Programming
    • Low-level Languages An assembly language command such as ADD X Y Z might mean add the values found at x and y in memory, and store the result in location z. Assembly language must be translated to machine language (zeros and ones) 0110 1001 1010 1011 The CPU can follow machine language 4 COMSATS Institute of Information Technology Object Oriented Programming
    • 5 COMSATS Institute of Information Technology Object Oriented Programming
    • Compilers Translate high-level language to machine language Source code  the original program in a high level language Object code  the translated version in machine language 6 COMSATS Institute of Information Technology Object Oriented Programming
    • Linkers Some programs we use are already compiled Their object code is available for us to use For example: Input and output routines A Linker combines The object code for the programs we write and The object code for the pre-compiled routines into The machine language program the CPU can run 7 COMSATS Institute of Information Technology Object Oriented Programming
    • Programming and Problem Solving Algorithm A sequence of precise instructions which leads to a solution Program An algorithm expressed in a language the computer can understand 8 COMSATS Institute of Information Technology Object Oriented Programming
    • Program Design Programming is a creative process No complete set of rules for creating a program Program Design Process Problem Solving Phase  Result is an algorithm that solves the problem Implementation Phase  Result is the algorithm translated into a programming language 9 COMSATS Institute of Information Technology Object Oriented Programming
    • Problem Solving Phase Be certain the task is completely specified What is the input? What information is in the output? How is the output organized? Develop the algorithm before implementation Experience shows this saves time in getting your program to run. Test the algorithm for correctness 10 COMSATS Institute of Information Technology Object Oriented Programming
    • Implementation Phase Translate the algorithm into a programming language Easier as you gain experience with the language Compile the source code Locates errors in using the programming language Run the program on sample data Verify correctness of results Results may require modification of the algorithm and program 11 COMSATS Institute of Information Technology Object Oriented Programming
    • 12 COMSATS Institute of Information Technology Object Oriented Programming
    • Procedural Languages • • • • • Examples of procedural languages: C, Pascal, Fortran A program in a procedural language is basically a list of instructions As programs become larger they are usually broken down into smaller units, such as functions, procedures, subroutines Functions can be grouped together into modules according to their functionality, objectives and tasks. Structured programming is a programming paradigm that to a large extent relies on the idea of dividing a program into functions and modules. 13 COMSATS Institute of Information Technology Object Oriented Programming
    • Problems with Structured Programming • Functions have unrestricted access to global data Function A: Function B: Function C: local data local data local data global data X global data Y • Large number of potential connections between functions and data (everything is related to everything, no clear boundaries) • makes it difficult to conceptualize program structure • makes it difficult to modify and maintain the program e.g. : it is difficult to tell which functions access the data 14 COMSATS Institute of Information Technology Object Oriented Programming global data Z
    • Problems with Structured Programming • data and function are considered as two separate entities • makes it difficult to model things in the real world • complex real world objects have both attributes and behaviours • attributes • people: name, date of birth, eye color, job title • cars: horse power, number of doors, color • behaviours • people: ask a person to bring you a beer • cars: apply the brakes, turn on the engine • attributes and behaviors alone are sufficient to realistically COMSATS Institute of Information Technology 15 Object Oriented Programming model real world objects but a unified view is needed
    • Object Oriented Programming Abbreviated OOP Used for many modern programs Program is viewed as interacting objects Each object contains algorithms to describe its behavior Program design phase involves designing objects and their algorithms 16 COMSATS Institute of Information Technology Object Oriented Programming
    • OOP Characteristics Encapsulation Information hiding Objects contain their own data and algorithms Inheritance Writing reusable code Objects can inherit characteristics from other objects Polymorphism A single name can have multiple meanings depending on its context 17 COMSATS Institute of Information Technology Object Oriented Programming
    • Object Oriented Approach Object functions data • Encapsulation: integrate data and functions into one object • Data hiding : data is hidden to the outside world and can only be accessed via the functions • In C++ functions are called membership functions in other languages they are called methods • Data items are called attributes or instance variables 18 COMSATS Institute of Information Technology Object Oriented Programming
    • Object Oriented Approach • separation: objects interact with each other only via their membership functions • separation helps to maintain the integrity of the entire program Object A functions Object C functions data 19 COMSATS Institute of Information Technology Object Oriented Programming data Object B functions data
    • Abstraction • An abstraction is a named collection of attributes and behavior relevant to model a given entity for some particular purpose real-world abstraction attributes software {data, data,…} entity behavior 20 COMSATS Institute of Information Technology Object Oriented Programming { method, method…}
    • Separation • independent specification of a visible interface and a hidden implementation • interface is some kind of contract between the object and the user of this object or module • separation is not restricted to object-oriented programming for example header files in standard C can be regarded as interfaces visible hidden 21 COMSATS Institute of Information Technology Object Oriented Programming interface Implementation
    • Structure of an Object Implementation Interface Object method method code code data method method 22 code code COMSATS Institute of Information Technology Object Oriented Programming
    • Examples of Objects 23 • physcial objects • vehicles in a traffic-flow simulation • electrical components in a circuit-design program • elements of a computer user environment • menus • graphic objects • data-storage constructs • arrays • linked lists • human entities • employees • students • collections of data • an inventory • an address book • user defined data types COMSATS Institute of Information Technology • time Object Oriented Programming • complex numbers
    • Example of a Class in C++ class someobject //declares a class { private: int somedata; //class data public: void setdata(int d) //membership function to set data { somedata=d; } int getdata() //membership function to get data { return somedata; } } 24 COMSATS Institute of Information Technology Object Oriented Programming
    • Classes versus Objects • A class is a prototype specification from which one can generate a number of similar objects • A class can be considered as an object factory. • An object is said to be a member or instance of a class • A class can be considered as a more complex data structure than an ordinary built-in data type • Standard C already knows the struct command for user defined data types: struct complex { double re; double im; }; complex x; 25 COMSATS Institute of Information Technology Object Oriented Programming
    • Instantiation of Objects person data: name, p_nummer, address, date of birth methods: getage(), changeaddress(newaddress) Class person data: Lena Brat, 761203-7111, Stureplan 4, female person data: Erik Olsson, 780605-4789, Hamngatan 3, male person data: Lars Backe, 671110-A562, Mälartorget 19, male 26 COMSATS Institute of Information Technology Object Oriented Programming
    • Relationships among Objects • Attribute: 27 One object uses as another object as an attribute, namely as member data, for example a Person contains an attribute Name. This type of relationship is also called a weak association or has-a relationship. Example: A Person has a Name • Association: One object uses another to help it carry out a task. Classes that collaborate are usually related through associations. This type of relationship is also called a uses relationship. Example: The object Driver invokes COMSATS Institute of Information Technology the method Brake Object Oriented Programming of the object BrakingSystem.
    • Relationships among Objects • Aggregation: Aggregation means that one object contains other objects. Aggregation is also called part-of relationship. Example: The class Adressbook contains many People Objects. • Composition: Composition is building objects from parts. It is a stronger type of aggregation in which the parts are necessary to the whole, namely they are permanently bound to the object and do not exist outside the object. A class Processor contains a CPU, Memory and I/O-Ports. 28 COMSATS Institute of Information Technology Object Oriented Programming
    • Relationships among Objects • Generalization Generalization is a relationship defined at the class level not the object level, which means that all objects of this class must obey the relationship. This is type of relationship is also called a is-a-kind-of relationship. Generalization in object oriented languages is realized by means of inheritance. Example: A car is a kind of vehicle. 29 COMSATS Institute of Information Technology Object Oriented Programming
    • Inheritance • In our daily lives we use the concept of classes divided into subclasses, for example vehicles are divided into cars, trucks, buses and motor cycles. • The principle in this sort of division is that each sub-class shares some common features with the base class from which it is derived, but also has its own particular features. base class Vehicle wheels engine Car 30 wheels sub-classes or engine COMSATS Institute of Information Technologyderived classes trunk trunk Object Oriented Programming Truck wheels engine trailer trailer
    • Inheritance • A sub-class also shares common methods with its super-class but can add its own methods or overwrite the methods of its super-class. base class Vehicle brake() start_engine() Car brake() start_engine() open_door() open_door() 31 COMSATS Institute of Information Technology Object Oriented Programming Truck sub-classes or derived classes brake() start_engine() open_door() pull_trailer()
    • Inheritance Terminology: • Car is a sub-class (or derived class) of Vehicle • Car inherits from Vehicle • Car is a specialization of Vehicle • Vehicle is a super-class (or base class) of Car • Vehicle is a generalization of Car • In C++ an object of a sub-class is substitutable for an object of the super-class, in other words an object of class Car can be used whenever an object of class Vehicle is required. 32 COMSATS Institute of Information Technology Object Oriented Programming
    • Reusability • Reusability means that a class that has been designed, created and debugged once can be distributed to other programmers for use in their own programs. • Similar to the idea of a library of functions in a procedural language. • The concept of inheritance provides an important extension to the idea of reusability, as it allows a programmer to take an existing class without modifying it and adding additional features and functionality. This is done by inheriting a new sub-class from the exisiting base class. 33 COMSATS Institute of Information Technology Object Oriented Programming
    • Polymorphism & Overloading • Polymorphism : using functions and operators in different ways, depending on what they are operating on. • Polymorphism allows it to manipulate objects without knowing their exact type but only their common property. for example, the classes Triangle and Circle both have their own (polymorphic) version of the method Draw, but a graphic routine that draws graphical elements does not have to know which object it manipulates. • Overloading: an existing operator, such as + or = is given the capability to operate on a new data type, for example define the operator + for the class Complex such that it realizes the addition of two complex numbers. 34 COMSATS Institute of Information Technology Object Oriented Programming
    • Polymorphism • polymorphism means ”having many shapes” • in C++ it refers to a situation in which an object could have any of several types • a polymorphic variable can refer to objects of different classes, for example a graphic object can be either a circle or a triangle • a polymorphic function or operator can take arguments of different types • example: int max(int a, int b); double max(double a, double b); 35 COMSATS Institute of Information Technology Object Oriented Programming
    • C++ and C 36 • C++ is derived from the language C • C++ is a superset of C, that means almost every correct statement in C is also correct in C++ • The most important elements added to C are concerned with classes, objects and object-oriented programming • New features of C++ • improved approach to input/output • standard template library (STL) container classes for vectors, lists, maps, etc. • reference type replaces pointers • const variables replaces #define statements • string data type replaces C-style strings char[] • new comment style augments C-style comments /* */ COMSATS Institute of Information Technology Object Oriented Programming
    • Software Life Cycle 1. 2. 3. 4. 5. 37 Analysis and specification of the task (problem definition) Design of the software (object and algorithm design) Implementation (coding) Maintenance and evolution of the system Obsolescence COMSATS Institute of Information Technology Object Oriented Programming
    • C++ History C developed by Dennis Ritchie at AT&T Bell Labs in the 1970s. Used to maintain UNIX systems Many commercial applications written in c C++ developed by Bjarne Stroustrup at AT&T Bell Labs in the 1980s. Overcame several shortcomings of C Incorporated object oriented programming C remains a subset of C++ 38 COMSATS Institute of Information Technology Object Oriented Programming
    • C++ Standard Library C++ programs Built from pieces called classes and functions C++ standard library Rich collections of existing classes and functions “Building block approach” to creating programs “Software reuse” 39 COMSATS Institute of Information Technology Object Oriented Programming
    • Basics of a Typical C++ Environment C++ systems Program-development environment Language C++ Standard Library 40 COMSATS Institute of Information Technology Object Oriented Programming
    • Basics of a Typical C++ Environment Editor Phases of C++ Programs: 1. Edit 2. Preprocess 3. Compile 4. Link 5. Load 6. Execute Program is created in the editor and stored on disk. Disk Preprocessor Disk Preprocessor program processes the code. Compiler Disk Compiler creates object code and stores it on disk. Linker Disk Loader Disk Primary Memory Linker links the object code with the libraries, creates a.out and stores it on disk Loader puts program in memory. . . . . . . Primary Memory CPU 41 COMSATS Institute of Information Technology Object Oriented Programming . . . . . . CPU takes each instruction and executes it, possibly storing new data values as the program executes.
    • A Sample C++ Program A simple C++ program begins this way #include <iostream> using namespace std; int main() { Statements; } 42 return 0; COMSATS Institute of Information Technology Object Oriented Programming
    • #include <iostream> using namespace std; int main() { cout << “Hello Worldn”; return 0; } 43 COMSATS Institute of Information Technology Object Oriented Programming
    • Example: Adding Two Integers #include <iostream> using namespace std; // function main begins program execution int main() { int integer1; // first number to be input by user int integer2; // second number to be input by user int sum; // variable in which sum will be stored cout << "Enter first integern"; // prompt cin >> integer1; // read an integer cout << "Enter second integern"; // prompt cin >> integer2; // read an integer sum = integer1 + integer2; // assign result to sum cout << "Sum is " << sum << endl; // print sum return 0; // indicate that program ended successfully } 44 COMSATS Institute of Information Technology Object Oriented Programming
    • Variables Location in memory where value can be stored Common data types  int - integer numbers  char - characters  double - floating point numbers Declare variables with name and data type before use int integer1; int integer2; int sum; Can declare several variables of same type in one declaration  Comma-separated list int integer1, integer2, sum; 45 COMSATS Institute of Information Technology Object Oriented Programming
    • Variables Variable names  Valid identifier  Series of characters (letters, digits, underscores)  Cannot begin with digit  Case sensitive 46 COMSATS Institute of Information Technology Object Oriented Programming
    • Input stream object >> (stream extraction operator)  Used with cin  Waits for user to input value, then press Enter (Return) key  Stores value in variable to right of operator  Converts value to variable data type  = (assignment operator)  Assigns value to variable  Binary operator (two operands)  Example: sum = variable1 + variable2; 47 COMSATS Institute of Information Technology Object Oriented Programming
    •  Comments Document programs Improve program readability Ignored by compiler Single-line comment  Begin with //  Preprocessor directives Processed by preprocessor before compiling Begin with # Include Directives #include <iostream> Tells compiler where to find information about items used in the program iostream is a library containing definitions of cin and cout 48 COMSATS Institute of Information Technology Object Oriented Programming
    •  Standard output stream object cout “Connected” to screen <<  Stream insertion operator  Value to right (right operand) inserted into output stream  Namespace Tells the compiler to use names in iostream in a “standard” way std:: specifies using name that belongs to “namespace” std std:: removed through use of using statements  Escape characters  Indicates “special” character output 49 COMSATS Institute of Information Technology Object Oriented Programming
    • Running a C++ Program C++ source code is written with a text editor The compiler on your system converts source code to object code. The linker combines all the object code into an executable program. 50 COMSATS Institute of Information Technology Object Oriented Programming
    • 51 COMSATS Institute of Information Technology Object Oriented Programming
    • 52 COMSATS Institute of Information Technology Object Oriented Programming
    • 1.4 Testing and Debugging Bug A mistake in a program Debugging Eliminating mistakes in programs Term used when a moth caused a failed relay on the Harvard Mark 1 computer. Grace Hopper and other programmers taped the moth in logbook stating: “First actual case of a bug being found.” 53 COMSATS Institute of Information Technology Object Oriented Programming
    • Program Errors Syntax errors Violation of the grammar rules of the language Discovered by the compiler  Error messages may not always show correct location of errors Run-time errors Error conditions detected by the computer at run-time Logic errors Errors in the program’s algorithm Most difficult to diagnose Computer does not recognize an error 54 COMSATS Institute of Information Technology Object Oriented Programming
    • Escape Sequence n Newline. Position the screen cursor to the beginning of the next line. t Horizontal tab. Move the screen cursor to the next tab stop. r Carriage return. Position the screen cursor to the beginning of the current line; do not advance to the next line. a Alert. Sound the system bell. Backslash. Used to print a backslash character. " 55 Description Double quote. Used to print a double quote character. COMSATS Institute of Information Technology Object Oriented Programming