oop6-1

79
PAN African e-Network Project PGDIT Object Oriented Programming Semester – 2 nd Session - 1 Dr. Bhawna Minocha

Upload: savoir001

Post on 16-Sep-2015

9 views

Category:

Documents


1 download

TRANSCRIPT

  • PAN African e-Network ProjectPGDIT

    Object Oriented Programming

    Semester 2nd

    Session - 1

    Dr. Bhawna Minocha

  • Welcome to

    Object Oriented Programming

  • Genesis of C++ Structured vs. Object Oriented Programming Basics Concepts of Object Oriented Programming Structure of C++ program C++ Comments A simple C++ program with explanation Using streams for input and output (cin , cout) Placement of variable declarations The const qualifier Executing a C++ program A Class in C++ Synonyms Practice Questions & answers

    Session Outline

  • GENESIS OF C++

    Factors that contributed to the evolution

    Increasing complexity of the problem domain.

    Difficulty in capturing the complexity of the problem domain through procedural languages(like C, Fortran, Pascal)

    Difficulty in modeling real-world objects through procedural languages.

  • GENESIS OF C++Growing demands on software in terms of

    Correctness

    Maintainability

    Reusability

    Scalability

    Openness and interoperability

    Integrity

  • GENESIS OF C++Commercial viability

    A huge investment in C lead to the incorporation of object oriented features with C leading to

    C++ is a superset to C and C++ = C +OOPs.

    C++ provides object-oriented programming (OOP).

    OOPs was invented to overcome the drawbacks of the pop(Procedure-Oriented Programming).

  • Structured Vs

    Object-orientedDevelopment

  • Structured Programming

    In the structured approach, the problem is viewed as a sequence of things to be done, such as reading, calculating and printing.

    A number of functions are written to accomplish these tasks.

    The primary focus is on functions. A typical program structure for procedural

    programming is shown in the next slide.

  • Main Program

    Function - 2Function - 1 Function - 3

    Function - 4 Function - 5

    Function - 6

    Typical structure of structure-oriented programs

  • Structured programming basically consists of writing a list of instructions for the computer to follow, and organizing these instructions into group known as functions.

    While we concentrate on the development of functions, very little attention is given to the data that are being used by various functions.

    In a multi-function program, many important data items are placed as global so that they may be accessed by all the functions.

    Each function may have its own local data.

  • Global Data Global Data

    Function - 1

    Local Data

    Function - 1

    Local Data

    Function - 1

    Local Data

    Relationship of data and functions in Structured programming

  • Global data is more vulnerable to an inadvertent change by a function.

    In a large program it is very difficult to identify what data is used by which function.

    In case we need to modify an external data structure, we should also revise all functions that access the data.

    Another serious drawback with the Structured approach is that it does not model real world problems very well.

    This is because functions are action-oriented and do not really correspond to the elements of the problem.

  • Object-Oriented programming paradigm

    Object-oriented programming (OOP) is organized around "objects" rather than "actions, data rather than logic.

    OOP treats data as a critical element in the program development and does not allow it to flow freely around the system.

    OOP allows us to decompose a problem into a number of entities called objects and then builds data and functions around these entities.

  • Functions

    Data

    Functions

    Functions

    Data

    Object B

    Object C

    Data

    Object A

    Organization of data and functions in OOP

  • Comparison of the Two Approaches

    Software projects are complex, and decomposition (divide-and-conquer) is the primary strategy to deal with its complexity by breaking a problem up into manageable units.

    Prior to object-oriented analysis and design, the most popular approach to decomposing a problem was Structured Analysis and Design, whose dimension of decomposition is primarily by function or process, resulting in a hierarchical breakdown of processes composed of sub-processes.

  • Object-oriented analysis and design emphasizes decomposing a problem space by objects rather than by functions.

    The following figure illustrates the primary distinction between the two approaches presented.

  • Structured A/DObject-Oriented A/D

    Decompose by functions or processes

    Decompose by objects or concepts

    System

    Report Fines

    Record Issues

    Add To Stock

    Book

    Library

    Catalog

    Librarian

    Library Management System

    Comparison b/w OOAD & SSAD

  • Distinction between POP and OOP Programming

    POP

    Procedure oriented programming.

    Emphasis is on procedure.

    Follows top-down approach.

    Data is not secure.

    Large programs are divided in to smaller programs known as functions

    OOP

    Object oriented programming.

    Emphasis is on data rather than procedure

    Follows bottom-up approach.

    Data is secure by encapsulation.

    Programs are divided in to what are known as objects.

  • Basic Concepts of Object Oriented Programming

    312

    45 6

    7

    1. Objects2. Classes3. Encapsulation4. Abstraction5. Inheritance6. Polymorphism7. DynamicBinding&

    MessagePassing

  • Objects Objects are often used to model real world entities

    that we normally find in everyday life. An object can be a person , place , thing ,concept or

    anything we see in the real world . Some common examples of an object include car ,book, computer , apple etc.

    The principal building blocks of object-oriented programming.

    Each object is a programming unit consisting of data (variables) and functionality (methods).

  • OBJECT:STUDENT

    DataData

    Functions

    Objectscontaindata(likeName,DOB,Marks)andfunctions(likeTotal,averageanddisplay)tomanipulatethatdata.

    1. Total2. Average3. Display

    ................

    12

    A

    B

    A. NameB. Date Of BirthC. Marks

    ....................

    3

    C

  • Each object possess the following characteristics. Each object has an identity and are distinguishable.Data and functions are binded together to form an

    object.Objects in the system communicate with each other

    using the concept of message passing.Objects store data which is manipulated by its

    functions. Since all software applications serve people living in the

    real world, then that software should mirror the real world as closely as possible, both in its workings and in its appearance :: thats the reason to use objects

    Objects

  • ClassA class is a general specification or description for a

    set of objects that defines their common structure (data), behaviour (methods), and relationships (inheritance).

    A class is a prototype that defines the variables and methods common to all objects of a certain kind.

    Once a class has been defined, we can create any number of objects belonging to that class.

    If fruit has been defined as a class, then the statement fruit mango; will create an object mangobelonging to the class fruit.

  • Why use classes? The object is a basic key concept of Object

    Oriented Programming but still we focus on classes because classes provide us the ability to generalize similar type of objects.

    Classes provide us a set of common definitions for similar type of objects.

    Operations can be written once for each class , so that all the objects in a class can take benefit from the code reuse.

  • Distinction between Object and Class

    Object

    Objects may be created and destroyed at run time.

    Data and functions that operate on that data are binded together to form an object.

    Object is an instance of a class.

    Table , chair , sofa are examples of objects.

    Class

    Once we have defined a class, it exists all the time a program is running

    A collection of similar type of objects is called a class

    Class is a set of object that share common attributes and behaviours.

    Furniture is an example of class which has table ,chair , sofa objects.

  • EncapsulationEncapsulation

    Encapsulation is the wrapping up of data and function into single unit called object.

    The only way to access the data of an object is through the function which are wrapped in the class.

    Consider two classes.Library class and a Student Class. The Library class encapsulates data (like Book Id,bookauthor book title, no. of copies) and functions like issue(),book_status() and book_description () in to a single unit. As shown in next slide. In the similar manner the Student class encapsulates data and functions as shown in next slide. The two classes are independent of each other.

  • Issue()Book_statusBook_description

    Roll noNameClass

    Input()Show()

    Student Class

    Book IdBook authorBook title

    Library Class

    Encapsulation

  • ADVANTAGES OF ENCAPSULATION

    With Encapsulation Data Hiding can be accomplished.

    It protects the data of a class from accidental manipulation or misuse by the functions which are outside the class.

    Any changes made in the data and functions of a class does not make any effect to other classes.

    Classes are independent of each other.

  • AbstractionAbstraction Simplicity is good; complexity is bad.

    Abstraction is a process that involves identifying the essential features without including the internal details.

    A good abstraction is the one that emphasizes details that are significant and suppresses details that are not.

    Let us take a real world example ::Consider an example of a Television which consists of features such as changing the channel ,ON/OFF switch etc. User interacts with television using interfaces like channel changer, volume controller, and power button without going in to internal details of the working of each of the interface. The user is not concerned about how it receives signals over the air. ,translate them and display on the screen. So,it shows how the internal complexity of working of the television is hidden from the user.

  • Abstraction In object oriented programming , classes uses the concept of Abstraction.

    A class encapsulates the relevant data and functions that operate on databy hiding the complex implementation details from the user . In other

    words ,user needs to focus on what a class does rather than how it will be implemented.

    The following diagram shows that the basic concept of Abstraction.

    Abstraction

  • Inheritance

    Inheritance is the process by which objects of one class acquire properties of objects of another class.

    Types of class in inheritance.1. Base class.2. Derived class.

    Grand Father

    Father

    // Base class

    // Derived class

  • Inheritance is the process by which one object acquires the properties of one or more other object. It supports the concept of hierarchical classification (top-down).

    An object need to define only those qualities that make it unique within its class.

    It implements "is-a" relationships between objects.

    Inheritance creates a hierarchy of related classes (types) which share code and interface.

    Inheritance

  • INHERITANCE EXAMPLES

    Base Class Derived Class

    Employee ManagerResearcherWorker

    Account Checking AccountSaving Account

  • Generalization/Specialization represents the is a relationship set, an essential element of the object oriented paradigm. The main idea in Generalization/ Specialization is that one object class (the specialization) is a subset of another (the generalization).

    A generalization-specialization (gen-spec) relationship states that one object is a kind-of (or is-a) the other, and that the other is a generalization of the object

    Generalization/Specialization

  • Specialization is either: the process of defining a new object based on a

    (typically) more narrow definition of an existing object, or

    an object that is directly related to, and more narrowly defined than, another object.

    A specialization relation requires that every instance of the subtype be an instance of the supertype.

    It is common to say that everything that is true for a generalization is also true for its corresponding specialization.

    Specialization

  • POLYMORPHISMThe word Polymorphism is derived from two Greek

    words Poly means many and morphs means forms. So , polymorphism means the ability to take many forms.

    Polymorphism means one name, multiple forms. It allows us to have more than one function with the same name in a program .

    It also allows overloading of operators so that an operation can exhibit different behaviors in different instances.

  • Basics of OOPPolymorphism Example

    Ex:-addition(+)

    For two numbers ,the operation will generate a sum. For two strings , then the operation would produce a

    third string by concatenation.

  • Basics of OOPDynamic BindingBinding refers to the linking of a function call to the

    code of the function to be executed in response to the function call. Binding is of two types::Static Binding or Early BindingDynamic Binding or Late Binding

    Static Binding:: In static Binding, the linking of function call to the code of the function to be executed in response to the function call is made at compile time.

    Static Binding:: In static Binding, the linking of function call to the code of the function to be executed in response to the function call is made at run time.

  • MESSAGE PASSING In Object oriented programming (OOP) different objects

    communicate with each other using the concept of Message Passing. From the programmer point of view ,message passing provides an easy way of modeling real world problems on the computer. Objects communicate with each other in the same way as human beings exchange messages among themselves.

    A message comprises of the name of the object , name of the function and any information (arguments) to be sent to the object. For example :If a user wants to check the balance of his account , he simply sends the message getbalance to the object account by passing the information account_no. as shown below

    account. getbalance (account_no) account:: Object Getbalance:: Message account_no :: Argument or Onformation

  • Structure Of C++ Program

    Documentation Section :: which includes the comments to tell the programspurpose. It improves the readability of the program.

    Preprocessor Directive :: includes preprocessor directives like # include, # define which is a message to the preprocessor

    Global Declaration Section:: includes global variables which are visible throughout the program. In general, use of global variables should be avoided.

    Class Section :: describes information about classes present in the program.

    Main Program Section:: from here the execution of program actually starts.Eg:: int main(){ // Executable Part }SubProgram Section :: includes user defined functions.

  • C++ Comments

    C++ supports the C comment format where /* begins a comment and */ ends it. The // also starts a comment in C++ (unless it is inside a string). Everything to the end of the current line is a comment.

    e.g., /* This is a comment */

    // This is also a C++ comment

    // This is invalidin the next line

    /* This is valid inthe next line */

  • Good practice: C++ style of comment is recommended as can be seen in the following example.

    C++ Comments

    C++ styleif(a>b){ //int temp=a; //swap a, b

    //a=b;//b=temp;

    }C styleif(a>b){ /*

    int temp=a; /*swap a,b*/a=b;b=temp; */

    }

  • A Simple program in C++ to add two numbers// To add two numbers#include // preprocessor directive#include int main() // main() function heading{

    int a , b , sum; // variable declarationcout > a; // Input statement cout > b; sum=a+b;cout

  • Explanation of the previous program

    The first line :: specifies the comment describing the purpose of the program. It is non executable statement.

    The second line :: contains a preprocessor directive that instructs the compiler to include the file iostream.h(Input /Output header file) at this point. This file must be included in the program to perform any Input /Output operations.Similarly the header file conio.h is handled.The fourth line :: main () is a entry point of a programs execution. Every C++ program must contain only one main function.It is necessary to specify the return data type of every function used in C++. The return type of main is always int. the last statement return 0; tells main to return value 0 to the calling environment. Any other value specified with return statement indicates that the program has not run properly.The remaining lines :: comprises the set of statements which includes variables declaration , input statements, and output statements.cin statement is used to input any value from the keyboard and cout statement is used to display any message or value on the screen.

  • On executing previous C++ program , we get

    Enter Number a=7 //(press enter)

    Enter Number b=7 //(press enter)

    Sum is 14

  • Streams

    The Standard Output Stream The name cout represents the standard output stream. It can be

    used to send messages to the standard output (the screen).

    The Standard Error Stream The name cerr represents the standard error stream. It can be

    used to send messages to the screen, especially from programs that have their standard output redirected to another file or device.

    The Standard Input Stream The name cin represents the standard input stream. It can be used

    to read data typed from the keyboard. Any built-in data type may be used with cout, cerr and cin without a

    format string, unlike printf.

  • 47

    Getting output onto the screen include the header file use cout

  • 48

    Getting input from the keyboard include the header file declare a variable of a suitable type

    eg int num_in; use cin

    eg cin >> num_in;

  • 49

    Getting input from the keyboard

    ##include

    int main( ){

    int x;cout x;cout

  • Placement of Variable Declaration C requires that all variables be declared at the beginning of a

    block. C++ allows the declaration of a variable anywhere in the code, but

    before it is referenced. Allows the placement of a variable closer to the code that uses it,

    which makes the program more readable.

    e.g.,

    main(){cout > num;cout

  • Basic Data Types

    Type Bytes Range

    Char 1 -128 to 127

    Unsigned char 1 0 to 255

    Signed char 1 -128 to 127

    Int 2 -32768 to 32767

    Unsigned int 2 0 to 65532

    signed int 2 -31768 to 32767

    Short int 2 -31768 to 32767

    Unsigned short int 2 0 to 65535

  • signed short int 2 -32768 to 32767

    Long int 4 -2147483648 to 2147483647

    signed long int 4 -2147483648 to 2147483647

    signed long int 4 0 to 4294967295

    Float 4 3.4E-38 to 3.4E+38

    Double 8 1.7E-308 to 1.7E+308

    Long double 10 3.4E-4932 to 1.1E+4932

    Basic Data Types

  • BOOLIt takes only two values: true or false

    true=1;false=0;

    eg: #include#includevoid main(){bool b=32;bool i=false;cout

  • output

    1 0 2 true

    NOTE: Some compilers(such as TurboC++ 3.0)do not support bool data type.However ,compilers like Dev-c++,Bortland C++ 5.5 etc support this data type.

  • PROGRAM TO SHOW RANGE OF INTEGER DATATYPE

    #includevoid main(){cout

  • output

    Minimum value of int = -32768 Maximum value of int =32767 Maximum value of unsigned int =65535 Maximum value of long int =2147483647 Maximum value ogf long int =-2147483648

  • The const Qualifier used to declare constants, as in ANSI C specifies that the variable is read-only, except during its one-

    time initialization. const variables can only be given values at initialization time. can be used as a replacement for constants defined with the

    #define directive. C++ allows const declarations in header files, unlike CE.g.:const int a=123;Good practice:Prefer const to preprocessor macro since const variable value is

    available to symbolic debugger unlike # defined values

  • DIFFERENCE BETWEEN #DEFINE AND CONST1. Const is better than #define.

    2. If we place const inside the function i.e. effect will be localized in that function whereas if it is placed outside the function, its effect will be global.

    3. But #define is always global. It cant be localized.

  • Executing any High level C++ involves following steps

    Developing the source code program

    Selecting and saving the appropriate file name .This saved file is known as source code file.

    Compile the program. After compilation the program changes to a object file if there are no errors.

    Now link the object code and other library codes that are required for execution. On linking correctly an executable code is formed.

    Now run the program to obtain the desired results.

    If answer is correct then stop otherwise check for some logical error.

  • Executing your C++ Program

    Invoking Compiler:: there are many C++ compilers like Borland C++,Turbo C++ etc. Well take Turbo C++ as an example.Change the directory to C:\cd TC (If TC directory)And then C:\TC\ cd BINResult :: C:\TC\BINMaking a New Program:: Select New from the file menu in the editor and type the file name as First.CPP (Note the extension)

    Typing your Program:: Type the program as specified in the discussed example in the editor window.

    Saving the Program:: After typing the C++ source code (program) save it to the disk by selecting SAVE from FILE menu.

    Running the program:: Once we type and edit our C++ program source code, we must compile the program by using ALT + F9

  • Executing your C++ Program

    Compiling the Program:: Whenever you compile a program, a compilation window appear on the screen. If there are no errors during compilation ,it will display Success :Press any key message. The entries for warning and errors will be zero and an object file with extension (.OBJ) is created. This Object file contains machine language instructions that can be executed by the computer.

    Running the program:: To Run A C++ program after compilation we use the RUN option of Run menu item or press CTRL + F9 keys from the keyboard. It will result in creating a file with the same name as the source file but with >EXE extension like FIRST.EXE

    The getch function:: in the program helps to display the result on the screen automatically.

  • A Class in C++

    Class is a user define data type.Class is a collection of objects of similar type.Class Declarations.

    class name{ Data types;Member functions};

  • What is a class ?

    A class is An abstract datatype similar to a C structure.

    A representation of objects and the sets of operations that can be applied to such objects.

    Class consists of Data members and methods.

  • Definition of a class

    General form of a class :Class class_name{

    Data Members;

    Methods;};

    e.g.,Class A{

    int i ;char *strng;Void f (int , char *);

    int g() ;};

  • Definition of a class (Contd)e.g.,Class Circle{

    int radius;int XCentre;int YCentre;

    int GetRadius ();int SetData;int GetXCentre ();int GetYCentre ();};

  • private, protected,public are called visibility labels.

    The members that are declared private can be accessed only from within the class.

    Public members can be accessed from outside the class also.

    In C++, data can be hidden by making it private.

    Encapsulation is thus achieved.

    Definition of a class (Contd)

  • DataFunctions

    FunctionsData

    Private area

    Public area

    Entry allowed

    No entry

    Definition of a class (Contd)

  • Synonyms

    Operations - "method selectors," "method interfaces," "messages," or "methods", services,member function, Instance Method

    Object - instance, class instance, surrogate, entity.

    Class - type Base Class - Super Class, Parent Class. Derived Class - subtype, subclass, Child

    class.

  • Member Variable - state variable, instance variable, data member, attribute, field, slot.

    Inheritance - subclassing, derivation, prefixing. Abstract Class - interface, protocol, type,

    virtual class, signature. Object name - object reference, Handle, object

    identifier.

  • Practice Questions 1

    Q1 Identify the drawback of using procedure-oriented programming, if any:a) Data is hidden from external functionsb) New functions can be added whenever

    necessaryc) Does not reflect real world problemsd) All of the above

  • Practice Questions 2

    Q2 Which one of the following OOP concepts enables reusability of components?a) Inheritanceb) Encapsulationc) Polymorphismd) All of the above

  • Practice Questions 3

    Q3 The concept of hierarchical classification is related to:a) Abstractionb) Inheritancec) Function overloadingd) None

  • Practice Questions 4

    Q4 Comments in C++ starts with _______ symbol.a) //b) \\c) **d) None of the above

  • Practice Questions 5

    Q5 return is an example of a a) Keywordb) Functionc) Statementd) Comment

  • Practice Questions 6

    Q6 The declaration of global variables must be madea)inside the functionb) outside the functionc) in a function header lined) None of the above

  • Practice Questions 7

    Q7 Consider the following code:cout

  • Answers

    Q1 c Q2 a Q3 b Q4 a Q5 a Q6 b Q7 d

  • Programming Practice Question Q1 Create a simple C++ program to

    display your name and fav. Color Q2 Create a simple C++ program to

    perform the four basic operations like (+,-,*,/).

    Q3 Write a program to read two numbers from the keyboard and display the larger value on the screen.

  • Thank You

    Please forward your query

    To :[email protected]: [email protected]