OOP 1-7

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

Transcript of OOP 1-7

  • 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]

  • PAN African e-Network ProjectPGDIT

    Object Oriented Programming

    Semester 2nd

    Session - 2

    Dr. Bhawna Minocha

  • Tokens Expression Decision Control Structures Loop Control Structures Practice Questions & answers

    Session Outline

  • C++ TOKENS

    Tokens are the smallest individual units in a program.

    Tokens are the various C++ program elements which are identified by the compiler.

    Various C++ Tokens are as: Keywords Identifiers Constants Operators Special characters (#,?)

  • KEYWORDS

    Keywords are the reserved words which have standard predefined meaning in C++.

    These cant be used as the names for the program variables or other user defined programs.

    Eg. float, int, enum, long ,double, switch etc.

  • IDENTIFIERSIdentifiers refers to the names of variables, functions, arrays, class etc created by the programmer.

    Rules for writing identifiers: Only alphabetic characters, digits and underscores are

    permitted. The name cannot start with a digit. Uppercase and lowercase letters are distinct(C++ is a

    case sensitive). Like RESULT variable is not the same as the result variable or the Result variable. These are three different variable identifiers.

    A declared keyword cant be used as a variable name.

  • VARIABLES

    Variable is the name given to location in memory where value of variable is stored.

    eg. a=20, stores the value 20 at memory location named as a.

    We must first declare a variable specifying which data type we want it to be.

    The syntax to declare a new variable isdatatype variable-name;

    Example int a; float mynumber;char a,b,c;

  • Declaration of variables The integer data types short, long and int can be

    either signed or unsigned based on the range of numbers needed

    Signed types can represent both +ve and vevalues,

    unsigned types can only represent +ve values (and zero)

    unsigned short int num; // only +ve values

    signed int balance; // +ve & -ve values

  • CONSTANTS

    Constants refers to the fixed values that do not change during the execution of a program.

    int a= 123 // decimal integer float b =12.34 // floating point integer char *s= AB // string constant-occupies 3

    bytes(includes the null character) char c= A // character constant- occupies only 1

    byte.

  • QUALIFIERS

    Qualifiers are the additional attributes to the data type.

    Eg. 12345L // long integer constant7865435UL // unsigned long integer

  • Expressions

    An expression is a combination of constants , variables and operators to form an executable statement which computes a value.

    The resultant value must be of valid data type that can be assigned to a variable.

    For example : sum=a+b; In the given statement ,the expression a+b consists of

    an operator + and operands a and b. The result of this expression will be assigned to variable sum.

  • Some Valid C++ Expressions

    Algebraic Expression

    ( a b ) / ( c + d )

    4 x2 + 3x + 5

    (sin2x cos2x)1/3

    X2 + y22 cos x

    C++ Expression

    ( a b ) / (c + d )

    4 *x*x +3*x +5

    pow (( sin (x) * sin (x) cos (x) * cos (x)),1/3)

    (x * x + y * y) / (2 * cos (x))

  • Operators

    An operator is a special symbol that specifies what operation is performed on one or more operands where an operand can be a variable , constant or expression.

    An operation is an action(s) performed on one or more operands that evaluates mathematical expression or change the data

    In C++, the operator can be unary , binary or ternary. If an operator operates on single operand then it is

    termed as an unary operator . If an operator operates on two operands ,it is called

    binary operator.

  • C++ provides a rich set of operators.Some of C++ operators are inherited from C language whilemany other new operators are introduced in to it.Operators Inherited from C Additional C++ Operators

    Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators Conditional Operators Unary Operators Type cast operator

    Stream Input Output Operator(>>,

  • Operators in C++

    312

    45 6

    7

    1. Arithmetic Operators 2. Relational Operators3. Logical Operators4. Bitwise Operators5. Increment/Decrement

    Operator6. Assignment Operators7. Conditional Operators8. Comma Operator9. Sizeof Operator10 Scope Resolution

    Operator11 Type cast operator

    8 9

  • Arithmetic OperatorsThe Arithmetic operators are used for mathematical calculations

    The arithmetic operators are binary operators that work on any built-in types.

    The following data shows 5 arithmetic operators with their meanings.

    Operator Meaning

    + Addition

    - Subtraction

    * Multiplication

    / Division

    % Modulus division

  • Arithmetic Operators:The operands acted on by arithmetic operators must represent numeric values. Thus the operands can be integer quantities, floating point quantities or characters. The Arithmetic operators when used with characters ,operate on ASCII values of the characters.

    If a=7 and b=3 (Integer)

    If a=10.5 and b=2.0 (float)

    a+b

    a-b

    a*b

    a / b

    a % b

    10

    4

    21

    2

    1

    12.50000

    8.500000

    21.00000

    5.250000

    Not applicable as per condition

  • Integer Division Integer division produces an integer result

    Truncates the result Examples 3 / 2 evaluates to 1 4 / 6 evaluates to 0 10 / 3 evaluates to 3

    MOD :: Produces the remainder of the division Examples 5 % 2 evaluates to 1 12 % 4 evaluates to 0 4 % 5 evaluates to 4

  • Sample program

    #include Output:

    int main() Enter the days 365

    { months = 12, days = 5

    int months,days;

    cout > days;

    months = days/30;

    days = days%30;

    cout

  • Operators and Precedence

    Consider mx + b Consider m*x + b which of the following is it equivalent to

    (m * x) + b m * (x + b)

    Operator precedence tells how to evaluate expressions Standard precedence order

    () Evaluate first, if nested innermostdone first

    * / % Evaluate second. If there are several,then evaluate from left-to-right

    + - Evaluate third. If there are several,then evaluate from left-to-right

  • Operator Precedence

    Example20 - 4 / 5 * 2 + 3 * 5 % 4

    (4 / 5)((4 / 5) * 2)((4 / 5) * 2) (3 * 5)((4 / 5) * 2) ((3 * 5) % 4)

    (20 -((4 / 5) * 2)) ((3 * 5) % 4)(20 -((4 / 5) * 2)) + ((3 * 5) % 4)

    Answer 17

  • Relational OperatorsWe often compare two quantities and depending on their relation take certain decision.

    Comparing the age of two person, price of two items.

    Relational operators are used to check relation between two operands.

    In other words, the operators used to make comparisons between two operands are called Relational Operators.

    Relational operators are binary operators and hence require two operands.

    The value of relational expression is either true or false.

    If It is 1(non zero) the specified relation is true and 0(zero) If the specified relation is false.

  • Operator Symbol

    Operation Performed

    Use Result

    =

    = =

    !=

    less than

    Less than or equal to

    Greater than

    Greater than or equal to

    Equal to

    Not equal to

    Exp1=exp2

    Exp1= =exp2

    Exp1 != exp2

    True if expr1 is less than expr2 else false

    True if expr1 is less than or equal to expr2 else false

    True if expr1 is greater than expr2 else false

    True if expr1 is greater than or equal to expr2 else false

    True if expr1 is equal to expr2 else false

    True if expr1 is not equal to expr2 else false

    Relational Operators

  • Relational Operators:

    OperatorsFirst Group

    Second Group

    =

    ==, !=

    ExamplesIf i=2, f=3.5 where I is integer type variable and f

    is floating type variable(i+f)>=5

    f > 3

    will give result true and return value 1.

    Will interpret it to be true andresult is 1.

  • Logical Operators:Logical operators are used to combine one or more relational expressions that results in formation of complex expressions known as logical expressions.

    Like Relational operators, the logical operators evaluate the result of logical expressions in terms of Boolean values that can only be true (non zero) or false(zero) according to the result of the logical expression.

    Operator Operation Performed Use

    &&

    ||

    !

    Logical AND

    Logical OR

    Logical NOT

    Expr1 && Expr 2

    Expr1 || Expr 2

    ! (expr)

  • Logical Operators:

    Expr1 Expr2 Expr1 && EXpr2

    Expr1 || Expr2

    ! (Expr 1)

    False

    False

    True

    True

    False

    True

    False

    True

    False

    False

    False

    True

    False

    True

    True

    True

    True

    True

    False

    False

    Logical Operators:The following table shows the operation of Logical AND ,logical OR and Logical NOT

  • Logical Operators:Examples

    Consider an example where x has an integer value 3 and y has a character value b then

    (x==3) && (y==b)

    (x4) || (y=a)

    ! (x==3)

    True

    False

    False

    False

  • Logical Operators Evaluation:In case of Logical AND expression if the first

    condition evaluates to FALSE then there is no need to evaluate the other conditions. Similarly in case of logical OR expression if the first condition evaluates to TRUE then there is no need to evaluate the other condition.

    Logical Operators Precedence:The Logical NOT (!) operator has a higher precedence

    than the others. The Logical AND (&&) operator has higher precedence than logical OR (||) operator.

    The Logical AND and OR operators have lower precedence than the relational and arithmetic operators.

  • Bitwise Operators:C++ provides an extensive bit manipulation

    operators for programmers who want to communicate directly with the hardware. These operators are used for testing bits or shifting them either right to left or left to right. The Bitwise operators are

    Operator Meaning&

    |

    ^

    >

    ~

    Bitwise AND

    Bitwise OR

    Bitwise exclusive OR

    Shift left

    Shift right

    ones complement

  • Assignment Operator:Assignment operator (=) is the most commonly used binary

    operator in C++. It evaluates the operand on right hand side and then assigns the resulting value to a variable on the left hand side. The right operand can be a variable, constant ,function call or expression. The general form of representing assignment operator is :: variable = expression/constant/function call

    For example ::

    A=3 ; // constant

    X=y+10; // expression

    Consider a statement x=y=z=3;

    Such type of statement in which a single value is given to a number of variables is called multiple assignment statement.

  • Assignment Operator (contd):

    That is value 3 is assigned to the variables x, y and z .The assignment operator (=) has a right to left associativity , so the above expression is interpreted as

    (x=(y=(z=3)));

    C has set of shorthand assignment operators of the form

    Assignment Operator Shorthand Operator

    a=a+1 a+=1

    a=a-1 a-=1

    a=a*(n+1) a*=n+1

    a=a/(n+1) a/=n+1

    a=a%b a%=b

  • Advantages of using shorthand operators:

    * What appears on left hand side need not be repeated and therefore it becomes easier to write.

    * The statement is more concise and easier to read

    * The statement is more efficientComparison of = and = =:

    The assignment operator(=) is used to assign a value to a variable where as the equality operator (= =) used to compare two operands.

    Note :: The assignment operator has lower precedence than arithmetic , relational , bitwise and logical operators.

  • Increment (++) & Decrement (--) Operator:

    In certain situations there is need to increrase or decrease a variable by 1 continuously for some time. So , C++ provides an Increment opertaor and decrement operator to increase or decrease the value of the operand by 1respectively.

    ++ m; or m++;

    -- m; or m--;

    ++m is equal to m=m+1 shorthand form :: (m+=1)

    --m is equal to m=m-1 shorthand form :: (m-=1)

    m=5

    y=++m

    The prefix operator adds 1 to the operand and then the result is assigned to a variable on left.

  • Two Ways of representing Increment (++) & Decrement (--) Operator:

    1) As a prefix i.e. operator preceded the variable Eg. ++i, --j

    2) As a postfix i.e. operator follows the variable Eg. i--, j++

    In case of Prefix increment operator (eg.++i) , the value of the variable will be first incremented then incremented value will be used in the expression in which it appears.

    In case of Postfix increment operator (eg.i++) , the current value of the variable in the expression in which it appears and then the value is incremented by 1.

    In order to understand the difference between prefix and postfix increment operator ,let us consider an example on the next slide.

  • Difference between Prefix and postfix Operators:

    1) Suppose an integer variable i holds a value 10, then on executing statement. j=i++;

    results in j=10 and i=11;Since it is a postfix operator so value of i (10) is first assigned to j and then incremented by 1 (i.e. 10+1=11)

    2) If instead of the above statement , we have a statement j=++i;

    then it results in j=11 and i=11 .Since it is a prefix increment operator so value of i is first incremented by 1 (i.e. 10+1=11) and then it is assigned to j(11).

    Note :: In the similar way , the postfix and the prefix decrement operator works.

  • Difference between Prefix and postfix Operators:

    Prefix increment operator Post fix increment operator

    #include#includevoid main(){int i=1;printf(i=%d\n,i);printf(i=%d\n,++i);printf(i=%d\n,i);getch();}

    #include#includevoid main(){int i=1;printf(i=%d\n,i);printf(i=%d\n,i++);printf(i=%d\n,i);getch();}

  • Prefix increment operator Post fix increment operator

    Output-1(No change)2(Alteration before execution)2 (No change)

    Output-1(No change)1(No change because alternation after execution) 2 (New incremented value by 1)

  • Conditional Operator or Ternary Operator:

    A conditional operator or Ternary operator (which operates on three operands) pair in C(?:) used to construct conditional expression of the form

    exp 1 ? exp 2 : exp 3

    Where exp 1 exp 2 and exp 3 are expressions.

    How it works:

    here exp1 is a test condition which is evaluated first. If it is true then expr2 is evaluated and this becomes the value of conditional expression. However if it is false then expr3 is evaluated and this becomes the value of conditional expression. The value of conditional expression can also be assigned to another variable.

  • Conditional Operator or Ternary Operator:

    Example: c= (a>b) ? a:b;

    j= (i>10)? 1:100;

    k= (a>b) ? cout

  • Conditional Operator or Ternary Operator

    To find greatest number among three numbers.

    e.g

    (a>b)?((a>c)?a:c):(b>c)?b:c)

    e.g7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2.5>3 ? a : b // returns the value of a, since 5 is

    greater than 3.

  • Conditional Operator or Ternary Operator

    #include#includevoid main(){int a=10 ,b=5,c;c=a>b?a:c;cout

  • The Comma OperatorThe comma operator is used quite differently from most C++ operators. The Comma operator is used to declare more than one variable in a single line. The comma operator associates from left to right and therefore the first variable is declared before the second variable and so on.

    For example :: int x , y, z;

    float a,b,c

    Here the comma operator is a separator in the variable declaration. This operator is also used in the for loop for multiple initialization.

  • The sizeof Operator

    is a unary operator that returns the number of bytes required to store a variable or a data type. The syntax of using sizeOf operator is

    Sizeof ( data type or variable)Consider the variables a,b of int and float data ypes respectively

    Sizeof (a); // returns 2

    Sizeof (b) ; // returns 4

    Sizeof( double) ; // returns 8

    The sizeof operator is very useful when transferring a program from one computer to another as number of bytes allocated to various data types may vary from computer to computer having different compilers.

  • EXAMPLE OF SIZEOF OPERATOR:

    void main()

    {

    int a;

    float b;

    double c;

    char d; output:

    cout

  • Scope resolution operator: is used to access

    the global variable.int a=20;

    int main()

    {

    int a=10;

    cout

  • Explicit type casting operator

    Type casting operators allow you to convert a data of a one type to another type.

    The simplest one, which has been inherited from the C language, is to precede the expression to be converted by the new type enclosed between parentheses (()):

  • Explicit type casting operator - ExampleBelow code converts the float number 3.14 to an integer value

    (3), the remainder is lost.int i; float f = 3.14; i = (int) f;

    Here the typecasting operator was (int). Another way to do the same thing in C++ is using the

    functional notation: preceding the expression to be converted by the type and enclosing the expression between parentheses:

    i = int ( f );

  • Language Constructs

  • Control Structures

    Control Statements are used to control the flow of program's execution. Control Structures enable us to execute a certain set of commands based on a condition.

    The condition should be specified at the design time and at run time ,the condition is evaluated, and depending on the result of the condition ,the block of code following the condition is executed . These structures are also known as decision structures.

    There are various control statements supported by C++ which are broadly categorized in to two ways :

    Decision control Statements Loop Control Statements

  • Decision Control Statements

    The decision control statements alter the normal sequential execution of statements of the program depending upon the test condition to be carried out at a particular point in the program. The decision to be taken regarding where the control should transfer depends upon the outcome of the test condition.

    C++ supports following decision constructs If If else statement Switch statement Go to statement

  • Selections & Decision

  • If then selection structure The If...Then selection structure performs an

    indicated action only when the condition is True; otherwise the action is skipped.

    Syntax of the If...Then selection If

    {statement(s);

    } The keyword if tells the compiler that a

    decision control statement(s) to be executed.

  • If then selection structure If the condition is true (non zero) then the

    statement immediately following is executed. If the condition is false then the statement is ignored and control passes to the next statement following the if construct.

    In case of a single statement , we may or may not require to enclose it in braces.

  • Program to check whether a number is even or not?

    #include #include int main(){

    clrscr();int num;cout>num;if (num % 2 ==0){

  • Program to check whether a number is even or not? (contd)

    {cout

  • If else selection structure In case of if statement , the block of statements are

    executed only when the condition is true otherwise the control is transferred to the next statement following the if block. But if some specific statements are to be executed in both the cases ( either comdition is TRUE or FALSE) the else statement is used.

    The if statement consists of keyword if followed by a statement or a block of statements, then a keyword else followed by another statement or a block of statements.

  • If then else selection structure Syntax of the If...else selection If

    {statement 1;statement 2;

    }else{

    statement 3;statement 4;

    }

  • Program to check whether a number is even or odd?

    #include #include Int main(){

    clrscr();int num;cout>sum;if (num % 2 ==0)

    cout

  • Program to check whether a number is even or not? (contd)

    elsecout

  • Nested IfElse selection structure In the if-else statement, the body of if block and else

    block consists of a set of statements. It is also possible that an entire if-else statement can occur either within the body of if statement or/and in the body of else statement

    Syntax of the Nested If...Then...Else selection structure

    You can use Nested If either of the methods as shown in next slides

  • Nested IfElse selection structure Method 1 If ( condition 1 )

    {if (condition 2 )

    statement 1;else

    statement 2;}else

    statement 3;

  • Nested IfElse selection structure Method 2 If ( condition 1 )

    statement 1;else{if (condition 2 )

    statement 2else

    statement 3;}

  • Program to calculate the greatest of three numbers using nested if-else statement

    #include #include Int main(){

    clrscr();int a,b,c;cout>a>>b>>c;if (a>b){

    if (a>c)

  • Program to calculate the greatest of three numbers using nested if-else statementcout
  • Program to calculate the greatest of three numbers using nested if-else statement

    getch();return 0;

    }Output:

    Enter three numbers (A,B,C) : 10 20 30C= 30 is greatest

  • IfElse if ladder In the programs involving multiple test conditions ,

    the nested if-else statements makes the program very difficult to write and understand especially if they are nested more deeply because as the number of test conditions go on increasing ,care must be taken to match multiple if-else constructs. In order to solve the problem ,there is another way to write the same statements using if else-if ladder.

    The Syntax of if else if ladder is shown in next slide.

  • IfElse if ladder Syntax If (condition 1)

    statement 1;else if (condition 2)

    statement 2;else if (condition 3)

    statement 3;...

    elsedefault statement;

  • 67

    Using a switch statement

    Which variable are you going to switch on? Which cases will you respond to? Can provide a default case Type the skeleton of the switch statement first

    and compile then flesh it out with cases remember the break statement at the end of

    each case

  • 68

    Using a switch statement

    switch(x){case 1:

    //statements here ...break;

    case 2://statements here ...break;

    default://statements here ...break;

    }

  • 69

    Using the switch statement

    switch(x){case 1:

    cout

  • The comparison of switch and if else statements

    The switch statement is a multi way decision making statement which selects one of several alternatives based on the value of single variable or expression. The switch statement is mainly used to replace multiple if else if statement. The if-else-if statement causes performance degradation as several conditions need to be evaluated before a particular condition is satisfied.

    The switch structure starts with a keyword switch followed by the expression enclosed in the parentheses. The value of the expression is compared with each of the labels . A case is normally terminated with the break statement.

  • Loops make it possible to repeat a section of code a number of times. This is used for doing calculations, searching and sorting lists etc.

    Start of LoopCode

    End of loop

    LOOPs

  • LOOPsIn order to understand the concept of loops , let us

    consider a simple program which calculates the cube of first 3 natural numbers.

    #include #include int main(){

    int a,b,c;a=1; cout

  • LOOPs (contd..)b=2;cout
  • Loop Structures Loop structures allow you to execute one or more lines

    of codes repetitively. Many tasks consist of trivial operations that must be repeated over and over again, and looping structures are an important part of any programming language.

    C++ supports the following Loop statements. dowhile Loop whileloop forloop

  • 75

    Loop structures -do while

    The do while loop is similar to the while loop except that its test condition is evaluated at the end of the loop instead at the beginning as in the case of while loop. So in the case of do while the body of the loop always executes atleast once even if the test condition evaluates to false during the first iteration.

    If the test condition evaluates to TRUE , the body of the loop is executed and it keeps on executing until the test condition is FALSE and then control transfer to the next executable statement following the do while loop.

  • 76

    Loop structures -do while

    The do while loop:

    do { statement;statement;

    } while( condition);statement;

    Equivalent to:

    // somethingwhile( condition) {

    // something}

  • 77

    Loop structures -while.... loop

    The while loop is used to carry out looping operations. It lets you execute a set of statements repeatedly as long as condition evaluates to true. It is mostly used in those cases where the programmer doesnt know in advance how many times the loop will be executed.

    If the test condition evaluates to TRUE , the body of the loop is executed and it keeps on executing until the test condition is FALSE and then control transfer to the next executable statement following the do while loop.

  • 78

    loop Structures - Iteration

    The while loop:while ( condition ) {

    statement1;statement 2;

    } ORwhile ( condition )

    statement;

    Equivalent to: for( ; condition ; ) {

    // do something}

  • Practice Questions

    Q1 What will be the value ox x after the following two operations::

    a = 10, b = 15

    x=(a

  • Practice Questions

    Q2 If x=2,y=4,z=10 then compute the following expression:

    a) x < y + z2 < 4 +102< 14true (1)

  • Practice Questions

    Q3 If x=2,y=4,z=10 then compute the following expression:

    a) y + z = = x - y

  • Practice Questions

    Q4 Which loops body is executed atleast once?

  • Practice Questions

    Q4 What is the difference between if (i= = j) and if (I = j) ?

  • Practice Questions 7

    Q5 ++x is an example of prefix operatorpostfix operator

  • Programming Practice Question Q1 Calculate the factorial of a number using

    for loop. Q2 Print the multiplication table of a given no.

    using do while loop Q3 Calculate the division of a student

    according to marks obtained in 4 subjects. Q4 Evaluate the expression ::

    d / b + a b % c * 5 where a=6 b=5 c=3 and d=10.

  • Thank You

    Please forward your query

    To :[email protected]: [email protected]

  • PAN African e-Network ProjectPGDIT

    Object Oriented Programming

    Semester 2nd

    Session - 3

    Dr. Bhawna Minocha

  • for loop Functions Storage classes Reference variable Parameter passing mechanism Function overloading Inline function Class Friend function

    Session Outline

  • For Loop The for Next loop is one of the oldest loop

    structures in programming languages. do Loop works well when we dont know how many times we need to execute the statements in the loop. When we know we must execute a specific no. of times ,however a for loop is a better choice.

    This is a loop with an in-built counter. The syntax is:for (initialization ; condition; increment/decrement){

    statements;}

  • ForNext Loop where

    initialization expression is used to initialize the loop control variable.

    Condition is a relational or logical expression that determines the number of iterations desired and whether the loop should continue iterating or not.

    The Increment/decrement expression modifies the value of the loopcontrol variable each time the loop is executed.

    The three expressions of the loop are separated ay two semi colons.

  • Loop Structures - Iteration

    The for loop:

    for(k = 0; k < 10; k++ ) { cout

  • Program to calculate the average of n numbers:

    #include #include int main(){

    clrscr();int n,num,sum=0;cout>n;cout

  • Program to calculate the average of n numbers:for (int i=1; i>num;sum=sum+num;

    }float avg= float(sum)/n;cout

  • Program to calculate the average of n numbers:

    Output:How many numbers? :5Enter the numbes10 12 20 30 60 // press enterAverage is = 26.4

  • Functions Functions are building blocks of the programs. They make the programs more modular and

    easy to read and manage. All C++ programs must contain the function

    main( ). The execution of the program starts from the

    function main( ).

  • FunctionThere are two kinds of functions1. library functions or built-in functions2.user defined functions

    Library functions string function-strcpy(),strcmp,strcat .mathematical functions-pow,sqrt,sin(x) etc

  • Functions The general form of the function is: -

    return_type function_name(parameter list){

    body of the function

    }

  • Functions The function consists of two parts function

    header and function body. The function header is:-

    return_type function_name(parameter);

  • Functions For example,

    int factorial(int n, float j)is the function header of the function

    factorial. The return type is of integer which means

    function should return data of type integer. The parameter list contains two variables

    n and j of type integer and float respectively.

  • FunctionsThree things to remember Function Declaration Function Calling Function Definition

    Function Declaration A call to the function cannot be made unless

    it is declared. The general form of the declaration is:-

    return_type function_name(parameter list);

  • Function For example function declaration

    int factorial(int n1,float j1);Another method int factorial(int , float);

    Arguments contain the actual value which is to be passed to the function when it is called should correspond with the data types of the parameters.

    Syntax of function calling isfunction name(argument list);

  • Types of Function

    Function with no argument and no return type

    Function with argument and no return type Function with no argument and return type Function with argument and return type

  • FunctionThe Return Statement and Return values A return statement is used to exit from the

    function where it is. It returns the execution of the program to the

    point where the function call was made. It returns a value to the calling code.

    The general form of the return statement is:-return expression;

  • Function The expression evaluates to a value which

    has type same as the return type specified in the function declaration. For example the statement,

    return(n);

    If a function has return type as void then return statement does not contain any expression. It is written as:-

    return;

  • //programtoaddtwonumbersusingfunctionswithargumentandnoreturntype.

    #include#includevoidadd(int,int);voidmain(){

    intc,d;printf(Entertwonumbers:);scanf(%d%d,&a,&b);add(a,b);getch();

    }

  • voidadd(intc,intd){

    inttemp;temp=c+d;printf(%d,temp);

    }

  • //programtoaddtwonumbersusingfunctionswithargumentandreturntype.#include#includeintadd(int,int);voidmain(){

    intc,d,sum;printf(Entertwonumbers:);scanf(%d%d,&a,&b);sum=add(a,b);printf(%d,sum);getch();

    }

  • intadd(intc,intd){

    intsum;sum=c+d;return(sum);

    }

    //programtoaddtwonumbersusingfunctionswithnoargumentsbutreturntype.#include#includeintadd();voidmain(){

  • intsum;sum=add();printf(%d,sum);getch();

    }

    intadd(){

    inta,b,sum;printf(Entertwonumbers:);scanf(%d%d,&a,&b);sum=a+b;return(sum);

    }

  • //programinwhichafunctionacceptsnoargumentsandreturnsnovalue.#include#includevoidfunc1();voidfunc2();voidmain();{

    func1();func2();func1();getch();

    }voidfunc1(){

  • inti;for(i=1;i
  • Reference Variable Provides an alternative name for a previously defined

    variable.

    Reference variable is created as followsDatatype &reference name = variable name

    For example: float &sum=total total is a float type variablesum is the alternative name declared to represent the

    variable total

  • Application in passing arguments to function Example void f(int &x)

    { x=x+10; }

    void main(){ int m=10;f(m);

    }When the function call f(m) is executed ,the following initialization

    occurs.int &x=m;

    x becomes an alias of m after executing the statement f(m)

    Such function calls are known as call by reference.

  • Storage Classes and Scope The storage class of a variable specify how long

    a variable remains in memory. In other words ,it determines the lifetime during which memory is associated with a variable.

    A variable which is defined inside a function is called a local variable. The memory is allocated to local variable each time the control enters the function and released when the control leaves the function.

    Also ,the scope of local variable is limited to the function in which it is declared and it cannot be accessed in other function.

  • #include#includeint x=5,y=10;//global variableint main(){int z=15//local variable of main()void abc();abc();cout
  • In this program ,z is local variable in thefunction main() and w is a local variable infunction abc().Their scope is limited only inthe functions in which they aredeclared.Hence variable z cannot beaccessed in the body of the functionabc().Similarly ,variable w cannot beaccessed in main().The lifetime of variablew lasts from the time function abc() isinvoked to the time the control exits fromthe function.

  • Global Variable-A variable which is defined outside all functions are called global variables .Global variable are also called external variables as they are defined externally to all the functions. i.e at the beginning.

    #include#includeint x=10; //Global variableint main(){int x=5; //local variable in function main()cout

  • Automatic Variable Automatic variable(s) are declared inside a

    block or function in which they are to beused.In other words,their scope is limited toonly the block or function where they aredeclared.

    Automatic variables are called so becausethey are created (i.e assigned memoryautomatically when the control enters theblock or function and are destroyed (i.erelease memory) automatically when thecontrol exits from the function.

  • Program to demonstrate the scope and lifetime of automatic variables?#include

    #includeint main(){auto int j=15; //declaration of automatic variable{auto int j=20;cout

  • Output:In innermost block j=20In function j=25In outer block j=15

    Declaration of automatic variableauto int x=1; //or int x=1;auto float z; // or float z; z is not initialized to

    any value in the declaration so it contains a garbage value.

  • Extern variable The global variable can be accessed by all

    the functions that follows its definition in asource file.These variable can be used toshare information in a program thatexpands across multiple files .

    If a global variable is defined in some fileand you want to use this variable in someother file in your multifile program thendeclare such variable as extern variableusing the keyword extern.

  • Suppose FileA.cpp which contains definition of global variable x

    int x; //global variable definitionvoid f1(){}void f2(){}//fileb.cpp that uses global variable xextern int x;//external variable declarationvoid f3(){x=20; // //Accessing external variable x defined in FileA.cpp}

  • Static variables A static variable when declared within a

    function retains its value between thesuccessive function calls.

    The scope of static variables declaredinside the function is same as that ofautomatic variable and its lifetime is sameas that of global variable except that itcomes into existence when the firstinvocation is made to the functioncontaining it.

  • Program of static variable#include#includevoid main(){void fun_count();fun_count();fun_count();fun_count();getch();}void fun_count(){static int i;i=i+1;cout
  • Output-

    This is function call no =1This is function call no =2This is function call no =3

  • Register variables

    Automatic variables are normally stored inmemory but in order to speed up thememory access to the variable ,we store itin register using register storage classspecification.

    A register variable can be declared asregister int counter=1;

    By default ,it is initialized to a garbage value,same as that of automatic variable.

  • Parameter passing mechanism-Call by value vs. call by reference

    When we write a function likef ( int x ) {

    cout

  • If we call function f() in main asmain() {

    int i =10;cout >> value of I before calling f() : >> i;f(i);cout >> value of I after calling f() : >> i;

    }

    Output will be :value of I before calling f() : 10

    Value of x 10value of X in f() : 3value of I after calling f() : 10

  • The value of i is set to 10 that is what is printed. When we pass I to f(), its value is set to X so X is

    10. Later we change X to 3, that is what is printed. The control comes back to main after calling f(),

    the I is still 10. Though we changed the value of parameter X in

    f(), but the changes are not reflected in i. This is because X is passed by value.

  • Pass by referenceWhen we write a function like

    f ( int& x ) {cout >> value of X in f() before change : >> x;x =3;cout >> value of X in f() before change : >> x;

    } Here x is passed by reference and not by value

    that means if we change the value of x in f(), there will be change in the value of argument that is sent at the time of f() call. This is called as pass-by-reference

  • If we call function f() in main asmain() {

    int i =10;cout >> value of i before calling f() : >> i;f(i);cout >> value of i after calling f() : >> i;

    }

    Output will be :value of I before calling f() : 10value of X in f() before change : 10value of X in f() before change : 3value of I after calling f() : 3

  • The value of i is set to 10 that is what is printed. When we pass I to f(), its value is set to X so X is

    10. Later we change X to 3, that is what is printed. The control comes back to main after calling f(),

    the I is 3 now. We changed the value of parameter X in f(), the

    changes are now reflected in i. This is because X is passed by reference.

  • Function Overloading

    Function overloading is the practice ofdeclaring the same function withdifferent signatures. The same functionname will be used with different numberof parameters and parameters ofdifferent type. But overloading offunctions with different return types arenot allowed.

  • Function Overloading A function is overloaded when same name

    is given to different function. However, the two functions with the same name will differ at least in one of the following.

    a) The number of parametersb) The data type of parametersc) The order of appearance

  • Function Overloading In general functions are overloaded when : 1. Functions differ in function

    signature. 2. Return type of the functions is the same.

  • #include class arith {public:void calc(int num1){cout
  • Function Overloading If an exact match is not found ,the

    complier uses the integral promotion to theactual argument such as

    float to double

  • Function Overloading Where ambiguity arises

    long square(long n);double square(double x);

    square(10);will cause error because int argument can be

    converted to either long or double (ambiguity)

  • Inline Function Inline functions are functions where the

    call is made to inline functions, the actual code then gets placed in the calling program.

  • Inline Function What happens when an inline function is

    written? When the program is compiled, the code

    present in function body is replaced in the place of function call

  • Reason for the need of Inline Function: a function call transfers the control from the calling

    program to the function and after the execution of the program returns the control back to the calling program after the function call.

    These concepts of function saved program space and memory space are used because the function is stored only in one place and is only executed when it is called.

    This concept of function execution may be time consuming since the registers and other processes must be saved before the function gets called.

    The extra time needed and the process of saving is valid for larger functions

  • Inline Function Inline function eliminates the cost of calls

    to small function

    The general format of inline function is as follows:

    inline datatype function_name(arguments)

  • Inline Function #include

    int multi(int);

    void main( ){int x;cout >x;cout

  • Inline Function Inline functions will save time and are

    useful if the function is very small. If the function is large, use of inline functions must be avoided.

    The inline directive will be totally of no use when used for functions which are:

    recursive long composed of loops

  • Introduction to CLASS Class: A Class is a user defined data type

    to implement an abstract object. Abstract means to hide the details. A Class is a combination of data and functions.

    Data is called as data members and functions are called as member functions.

  • Data Members Data member or member functions may be

    public, private or protected.

    Public means data members or member functions defining inside the class can be used at outside the class.( in different class and in main function)

  • Data Members Private means data members and member

    functions cant be used outside the class.

    Protected means data member and member functions can be used in the same class and its derived class (at one level) (not in main function).

  • Data Members

    PRIVATE

    PUBLIC

  • Class Example (Problem)#include#includeclass student{int rollno;char name[20];};

    void main(){student s;couts.rollno;cout

  • Class Example (Solution)#include#includeclass student{public:int rollno;char name[20];};

    void main(){student s;couts.rollno;cout

  • Member Function Defining Inside the Class#include#includeclass student{int rollno;char name[20];public:void getdata(){coutrollno;cout
  • Member Function Defining Outside the Class#include#includeclass student{int rollno;char name[20];public:void getdata();void putdata();};void student :: getdata(){coutrollno;cout
  • Array of Class ObjectsProblem:

    #include#includeclass student{int rollno;char name[20];public:void getdata();void putdata();};void student :: getdata(){coutrollno;cout

  • Array of Class ObjectsSolution:

    #include#includeclass student{int rollno;char name[20];public:void getdata();void putdata();};void student :: getdata(){coutrollno;cout

  • Memory Allocation of Objectclass student{int rollno;char name[20];int marks;}; student s;

    rollno 2 bytes

    name- 20 bytes

    marks- 2 bytes

    24 bytes s

  • Friend function

    In principle, private and protected members of a class cannot be accessed from outside the same class in which they are declared.

    However, this rule does not affect friends. Friends are functions or classes declared

    with the friend keyword.

  • Friend Function A friend function has full access rights to

    the private members of the class. invoked like normal function Cant access member names directly and

    has to use an object name and dot membership operator with each member name.

  • Declared in either public or the private part of a class

    Object as its arguments

    Friend Function

  • Friend Function

    Class sample{int a,b;public: void setdata(){ a=25; b=40;}friend float mean(sample s);};float mean (sample s){ return float (s.a+s.b)/2.0;}void main(){sample x;x.setvalue();cout

  • A function friendly to two classesClass ABC; //forward declarationClass XYZ{int x;public: void setvalue(int i){x=i;}friend void max(XYZ,ABC);};

  • A function friendly to two classesClass ABC{int a;public: void setvalue(int i){a=i;}friend void max(XYZ,ABC);};void max(XYZ m , ABC n){ If (m.x>=n.a)cout
  • A function friendly to two classes

    void main(){ABC a;a.setvalue(10);XYZ x;x.setvalue(20);max(x,a);getch();}

  • 1. Which of the following is/are storage class

    a)Automaticb)staticc)registerd)all of the above

  • Q.no 2 When you pass a variable _____, C++ passes only the contents of the variable to the receiving function

    A. by referenceB. by valueC. globally D. locally

  • 3 What is function overloading

    a)calling a function from another function

    b)Having more than one function of same name

    c)calling a function from itself

    d)there is no such term in c/c++

  • 4 When the compiler cannot differentiate between two overloaded constructors, they are called

    A overloadedB.destructedC.ambiguousD.dubious

  • Thank You

    Please forward your query

    To :[email protected]: [email protected]

  • PAN African e-Network ProjectPGDIT

    Object Oriented Programming

    Semester 2nd

    Session - 4

    Dr. Bhawna Minocha

  • Session outline- Inline Functions Class Array of class objects Memory Allocation of objects Friend function Static data member and Static functions Default Arguments Constructor (Constructors in Array of Objects, Constructor overloading,

    Copy Constructor)

    Destructor

  • Inline Function Inline functions are functions where the

    call is made to inline functions, the actual code then gets placed in the calling program.

  • Inline Function What happens when an inline function is

    written? When the program is compiled, the code

    present in function body is replaced in the place of function call

  • Reason for the need of Inline Function: a function call transfers the control from the calling

    program to the function and after the execution of the program returns the control back to the calling program after the function call.

    These concepts of function saved program space and memory space are used because the function is stored only in one place and is only executed when it is called.

    This concept of function execution may be time consuming since the registers and other processes must be saved before the function gets called.

    The extra time needed and the process of saving is valid for larger functions

  • Inline Function Inline function eliminates the cost of calls

    to small function

    The general format of inline function is as follows:

    inline datatype function_name(arguments)

  • Inline Function #include

    int multi(int);

    void main( ){int x;cout >x;cout

  • Inline Function Inline functions will save time and are

    useful if the function is very small. If the function is large, use of inline functions must be avoided.

    The inline directive will be totally of no use when used for functions which are:

    recursive long composed of loops

  • Introduction to CLASS Class: A Class is a user defined data type

    to implement an abstract object. Abstract means to hide the details. A Class is a combination of data and functions.

    Data is called as data members and functions are called as member functions.

  • Introduction to CLASS Class: A Class is a user defined data type

    to implement an abstract object. Abstract means to hide the details. A Class is a combination of data and

    functions. Data is called as data members and

    functions are called as member functions.

  • Data Members Data member or member functions may be

    public, private or protected.

    Public means- data members or member functions defining inside the class can be used at outside the class.( in different class and in main function)

    Private means -data members and member functions cant be used outside the class.

    Protected means data member and member functions can be used in the same class and its derived class (at one level) (not in main function).

  • Data Members

    PRIVATE

    PUBLIC

  • Class Example (Problem)#include#includeclass student{int rollno;char name[20];};

    void main(){student s;couts.rollno;cout

  • Class Example (Solution)#include#includeclass student{public:int rollno;char name[20];};

    void main(){student s;couts.rollno;cout

  • Member Function Defining Inside the Class#include#includeclass student{int rollno;char name[20];public:void getdata(){coutrollno;cout
  • Member Function Defining Outside the Class#include#includeclass student{int rollno;char name[20];public:void getdata();void putdata();};void student :: getdata(){coutrollno;cout
  • Array of Class Objects#include#includeclass student{int rollno;char name[20];public:void getdata();void putdata();};void student :: getdata(){coutrollno;cout
  • Memory Allocation of Objectclass student{int rollno;char name[20];int marks;}; student s;

    rollno 2 bytes

    name- 20 bytes

    marks- 2 bytes

    24 bytes s

  • Friend function In principle, private and protected

    members of a class cannot be accessed from outside the same class in which they are declared.

    However, this rule does not affect friends.

    Friends are functions or classes declared with the friend keyword.

  • Friend Function A friend function has full access rights to the

    private members of the class.

    invoked like normal function

    Cant access member names directly and has to use an object name and dot membership operator with each member name.

  • Declared in either public or the private part of a class

    Object as its arguments

    Friend Function

  • A function friendly to two classesClass ABC; //forward declarationClass XYZ{int x;public: void setvalue(int i){x=i;}friend void max(XYZ,ABC);};

  • A function friendly to two classesClass ABC{int a;public: void setvalue(int i){a=i;}friend void max(XYZ,ABC);};

    void max(XYZ m , ABC n){ If (m.x>=n.a)cout

  • 24

    STATIC DATA MEMBERS

    Same as static variables in C Its value is initialized to zero when the first

    object of its class is created. When a class field is static, only one

    memory location is allocated All members of the class share a single

    storage location for a static data member of that same class.

  • Using Static Class Members When you create a non-static variable

    within a function, a new variable is created every time you call that function

    When you create a static variable, the variable maintains its memory address and previous value for the life of the program

    Static variables are normally used to maintain values common to entire class.

  • class Product{static int count;int number;

    public: void getdata(int a)

    {number=a;count++; }

    void getcount(){cout

  • Static Class Member

    Output:-count: 0count :0count:0After reading datacount:3count :3count :3

  • The type and scope of each static variable must be defined outside the class definition.

    While defining static variable some initial value can also be assigned to the variable.

    Eg. int Product:: count=10;

  • 29

    Using Static Functions Member function can be declared as static. A static function can have access to only other

    static members declared in the same class. A static member function can be called using the

    class name instead of its objects.Class_name:: function_name();

    Static functions cannot access non-static variables

    Non-static functions can access static variables (provided there is an object)

  • Class Test{

    int code;static int count;

    public:void setcode(){code= ++count;}void showcode(){cout

  • Output count = 2count = 3code=1code=2code=3

  • Default Arguments Default argument is useful in situations

    where a argument has the same value in most function calls.

    When the desired value is different from the default value, the desired value can be specified explicitly in function call. This changes the default value of the argument to be overridden for the duration of function call.

  • Default Arguments e.g- Consider example of a bank which

    introduces a new money deposit scheme where rate of interest is fixed to 5.5% per annum.

    If we want to calculate the simple interest on amount deposited by different customers under this scheme, we have to make a function SI() containing three parameters Principal(P),Rate of Interest r and Time period t .On calling this function for different values, we find the values of arguments r and t remain the same for each time, we need to pass only one argument.

  • Default Arguments#include#includefloat SI(float p,float r=5.5,float t=1.0);// function

    declarationvoid main(){float k;k=SI(10000); //equivalent to k=SI(10000,5.5,1.0);cout

  • Default Arguments

    float SI(float p,float r,float t){float sil=(p*r*t)/100;return sil;}Output- Simple interest=550

    Simple interest=720

  • A constructor is a special member function having same name as that of the class to which it belongs.

    It is used to initialize some valid values and allocate resources to the data members of an object.

    It is executed automatically when an object of a class is created.

    It does not have any return data type, not even void.

    Constructor

  • Class classname{

    .public:

    classname(parameter list); // constructor declaration .

    };Classname:: classname(parameter list)

    //constructor definition.{}They can also be defined inside the class as other

    member functions.

  • #includeclass Rectangle{private: int len, br;public:Rectangle(){

    len=5, br=4;}int area(){return (len*br);}};

    void main(){Rectangle r1;

    cout

  • The constructor to which no arguments are passed is also called default constructor

    Each time an object is created, a constructor is invoked.

    We can declare more than one constructor in a class (constructor overloading)

    Constructors can have default arguments. Constructors should always be declared in

    the public section of class.

    Constructors cannot be inherited.

  • Parameterized constructorsclass Rectangle{private:

    int len, br;public:Rectangle(int a, int b){

    len=a, br=b;}int area(){return (len*br);}};

    void main(){Rectangle r1(5,4);Rectangle r2(8,6);cout

  • Constructor Overloading It allows a class to have more than one

    constructors that have same name but differ in terms of number of parameters or parameters datatype or both.

  • #includeClass Rectangle{private:

    int len, br;public:

    Rectangle(){

    len=0, br=0;}Rectangle(int a){

    len=br=a;}Rectangle(int a, int b){

    len=a, br=b;}

    int area(){return (len*br);} };void main(){Rectangle r1;Rectangle r2(5);Rectangle r3(7,8);

    cout

  • Output-Area of first rectangle=0Area of square =25Area of second rectangle=56

  • Constructors in Array of Objects When an array of objects is defined then a

    default constructor is defined for each object of array.

    It means that each object of a array is initalized with same set of values using default argument constructor.

    Rectangle r[20]; // Each object of array invokes default constructor for initializing its data members.

  • class Rectangle{private:

    int length, breadth;public:Rectangle(int a, int b)

    {length=a, breadth=b;

    }void showarea(){cout

  • Output-Displaying Areas of rectanglesarea is 30area is 08area is 15

  • Copy Constructor It is a constructor that creates a copy of an

    existing object. It creates a new object using an existing

    object of the same class and initialize each data member of newly created object with corresponding data members of existing object.

  • e.g counter c1(10); counter c2(c1); The above statement creates object c2 and

    initialize it with values of c1.

    When c2 is created, a copy constructor is invoked

  • class counter{int count;public: counter(int c)

    { counter=c;}counter(counter &ob){

    cout

  • Output-Copy constructor Invokedcount =10count =10

  • counter c2(c1) is equivalent tocounter c2=c1;

    Imp: object passed to copy constructor. should be passed by reference and not by value.

    counter(counter &ob) is copy constructor which takes single argument ob which is reference to object c1 of class counter.

  • Destructor

    A destructor is a member function which helps to deallocate the memory allocated to an object.

    It has the same name as that of a const. but preceded by a tilde(~) symbol.

    It is executed automatically when objects of a class is destroyed.

    Like constructor, it does not have any return data type and not even void.

    A destructor does not accept any parameters. A class can have only one destructor and hence

    cannot be overloaded.

  • Syntax:class classname{.public:

    ~ classname(); //destructor declaration

    };classname:: ~classname() //destructor definition{.}

  • Destructor must be declared in public section of the class so that it is accessible to all its users.

    If we dont supply our own destructor , compiler will supply one implicit (default) destructor.

    Destructors are invoked automatically whenever the objects leave the block where they are defined. (means as soon as it encounters curly brace} )

    Objects are always destroyed in the reverse order of their creation

  • class counter{

    int id;public:

    counter(int i){id =i;

    cout

  • Output-Constructor of object with id 1 runsConstructor of object with id 2 runsConstructor of object with id 3 runsend of mainObject with id 3 destroyedObject with id 2 destroyedObject with id 1 destroyed

  • Q.No 1) Which of the following is not a type of constructor?

    A. Friend ConstructorB. Copy constructorC. Parameterized constructorD. Default constructor

  • Q.No 2) Which of the following concept of oops allows compiler to insert arguments in a function call if it is not specified?

    A. Call by valueB. Call by pointersC. Default argumentsD. Call by reference

  • Q.No 3) Which of the following statement is correct?

    A. Constructor is called at the time of declaration of an object.

    B. A constructor is called at the time of use of an object.

    C. A constructor is called at the time of declaration of a class.

    D. A constructor is called at the time of use of a class.