1 ©copyright 2004, cognizant academy, all rights reserved object oriented programming introduction

174
©Copyright 2004, Cognizant Academy, All Rights Reserved 1 OBJECT ORIENTED PROGRAMMING INTRODUCTION

Upload: annabel-short

Post on 19-Jan-2016

218 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 1

OBJECT ORIENTED PROGRAMMING

INTRODUCTION

Page 2: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 2

Course Objective & Outline

Course Objective:After completing this course, you will be able to understand the importance of OOPS in programming paradigm and basic terminology’s involved into OOPS.

Course Flow:

1Programming

paradigms

2OOPS

Concepts

3Functions in

C++

5Inheritance

6Polymorphism

4Classes and

Objects

Page 3: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 3

1 Programming Paradigms : Overview

Introduction:

Paradigm: (One that serves as a pattern or model)

• A set of scientific and metaphysical beliefs that make up a theoretical framework within which scientific theories can be tested, evaluated, and if necessary revised" (Cambridge dictionary of philosophy).

• A set of assumptions, concepts, values, and practices that constitutes a way of viewing reality for the community that shares them, especially in an intellectual discipline.

Page 4: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 4

Programming paradigm:

• A paradigmatic style of programming (compare with a methodology which is a paradigmatic style of doing software engineering).

• Provides (and determines) the view that the programmer has of the execution of the program.

Programming Paradigms : Overview

Page 5: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 5

Programming Paradigms : Overview

Objective:

After completing this module, you will be able to understand the following programming paradigms.

1. Procedural programming

2. Structured programming

3. Modular programming

4. Functional programming

5. Object-oriented programming

Page 6: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 6

Procedural Programming

Sub-programs

Global data

• Conventional top-down approach

• Programming paradigm based upon the concept of the procedure call (Procedures - also known as routines, subroutines, Sub-programs, methods, or functions)

Page 7: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 7

Procedural Programming

• Works well for small programs and individual algorithms

• Significant ease of maintainability and readability of code

• More flexible code

Possible benefits:

• The ability to re-use the same code at different places in the program without copying it.

• An easier way to keep track of program flow than a collection of "GOTO" or "JUMP" statements.

• The ability to be strongly modular or structured.

Page 8: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 8

Structured Programming

• Can be seen as a subset or sub discipline of Procedural programming.

• A hierarchy of modules is used, each having a single entry and a single exit point, in which control is passed downward through the structure without unconditional branches to higher levels of the structure.

Modules

Global data

Local Data Local Data Local Data Sub-programs

Page 9: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 9

• Three types of control flow are used:

- sequence

- selection

- iteration

Structured Programming

Y/N

Page 10: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 10

• Easy to understand the program, leading to improved reliability

• Often (but not always) associated with a "top-down" approach to design

• Lot of dubiousness in this case leaded to evolution of Object Oriented Programming Paradigm

Structured Programming

Page 11: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 11

Modular programming

• A software engineering technique (decomposition method) in which no component in a complex system should depend on the internal details of any other components (DanIngalls)

• May involve breaking down complex tasks into many different modules.

• Module – A component of a larger system that operates within that system independently from the operations of the other components of the system.

• Ad-hoc method of handling complexity.

Page 12: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 12

Functional programming

• Treats computation as the evaluation of mathematical functions.

• Emphasizes the evaluation of functional expressions, rather than execution of commands.

• Expressions are formed by using functions to combine basic values.

• Immutable(inflexible) program rather than modify state to produce values, constructs state from older pieces of state in the program.

Page 13: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 13

Program is composed of a collection of individual units, or objects, as opposed to a traditional view in which a program is a list of instructions to the computer

Object Oriented Programming

Data variable

Member Function

Data variable

Member Function

Data variable

Member Function

Object A

Object B

Object C

Page 14: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 14

Object Oriented Programming

• Does not deal with programming in the sense of developing algorithms or data-structures

• Focuses on ADT

Page 15: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 15

POA Vs OOA

Director Cell

H/W Components Room

Service Engineer Room

System assembled with the supplied H/w components

Send H/w + Instructions to assemble the system

Fetch Components

Procedure Oriented Approach:

Page 16: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 16

Object Oriented Approach:

Page 17: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 17

Object Oriented Programming

• Does not deal with programming in the sense of developing algorithms or data-structures, but must be studied as a (collection of) means for the organization of programs and, more generally, techniques for designing programs

• Focuses on ADT (Abstract Data Type - a collection of values and a set of operations on those values, that collection and those operations from a mathematical construct that may be implemented using a particular hardware or software data structure)

Page 18: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 18

Programming Paradigms : Summary

• Programming paradigm is a paradigm for programming computer programs or more generally software or software systems development.

• Procedural programming - composed of one or more units or modules-either user coded or provided in a code library.

• Structured programming - a subset or subdiscipline of procedural programming.

• Modular programming – involves breaking down complex tasks into many different modules and that is where modular programming comes into picture.

• Functional programming - treats computation as the evaluation of mathematical functions.

• Object oriented programming - simulates real world objects.

Page 19: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 19

2. Object Oriented Programming Concepts and C++

Introduction:In this Module we are going to get an understanding of basic concepts of Object Oriented Programming.

Objective: After completing this module, you will be able to understand,– Class and Object– Data Abstraction– Encapsulation– Inheritance– Polymorphism– History of C++– Attributes of Class– Object Terminology– Benefits of OOP

Page 20: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 20

Class & Object

Object:• An Object is a combination of data and behavior.• Object behavior is referred using terms such as functions,

member functions, methods or operations. • Data characterizes the state of an object.

Class:• Description of common properties of objects that belong to

the class i.e., collection of objects with common characteristics.

• A class does not exist in the memory of computer during program execution.

• e.g.: Writing material is a class. Pen and Pencil are objects of the class.

Page 21: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 21

Class & Object

Accountacct_nonamebalancewithdraw()deposit( )

Accountacct_nonamebalancewithdraw()deposit( )

431245Patrick50567.78

431245Patrick50567.78

431246Meyer35567.78

431246Meyer35567.78

Account:acct1 Account:acct2

Page 22: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 22

What’s Object Oriented programming?

Objects:

• Packaging data and functionality together into units within a running computer program;

• The basis of modularity and structure in an object-oriented computer program.

• Self contained and should be easily identifiable.

• In an object-oriented environment, software is a collection of discrete objects that encapsulate their data as well as the functionality to model real-world objects.

Page 23: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 23

Advantages Of Object Orientation

• Modularity: Since the whole system is being modeled as classes and various methods are divided according to the respective functionalities in respective classes modularity increases.

• Deferred Commitment: Since classes can be modified without modifying the actual code where the classes are being used, flexibility towards the commitment increases (Easier maintenance). The internal workings of an object can be redefined without changing other parts of the system.

• Reusability: Since defining classes through inheritance helps in reusability thus faster production.

Page 24: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 24

Advantages Of Object Orientation

• Higher Quality: Since deriving classes from existing classes which are working successfully.

• Reduced cost: Because of reusability

• Increased Scalability: Easier to develop large systems from well tested smaller systems.

Page 25: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 25

Abstraction

"A view of a problem that extracts the essential information relevant to a particular purpose and ignores the remainder ofthe information." - [IEEE, 1983]

• Each object in the system serves as a model of an abstract "actor" that can perform work, report on and change its state, and "communicate" with other objects in the system, without revealing how these features are implemented.

• Denotes the essential characteristics of an object that distinguishes from all other kinds of objects.

• Focuses on similarities while temporarily ignoring differences.

Page 26: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 26

Data abstraction is the process of distilling data down to its essentials, grouping the pieces of data that describe some entity, so that programmers can manipulate that data as a unit

• Projecting essential features without including the background details

• Building up data types from the predefined data types is data abstraction.

• Object-oriented programming can be seen as an attempt to abstract both data and code.

Data Abstraction

Page 27: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 27

Kinds of data abstraction :

Association - A relationship between two classes that represents the existence of a set of links between objects of the two classes

• Attribute - A simple data item present in all the instances of a class

• Class - A software module that provides both procedural and data abstraction. It describes a set of similar objects, called its instances

• Data type - A name or label for a set of values and some operations which one can perform on that set of values.

Data Abstraction

Page 28: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 28

Encapsulation

• Bundling of the data and methods together

• Ensuring that users of an object cannot change the internal state of the object in unexpected ways; only the object's own internal methods are allowed to access its state.

• Each object exposes an interface that specifies how other objects may interact with it. Other objects will rely exclusively on the object's external interface to interact with it.

Page 29: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 29

Information Hiding

"The process of hiding all the details of an object that do not contribute to its essential characteristics; typically, the structure of an object is hidden, as well as the implementation of its methods. The terms information hiding and encapsulation are usually interchangeable."

- [Booch, 1991] • Hiding all the details of an object that does not contribute to

its essential characteristics.

• Why is it needed? ( We separate the implementation details from the actual use )

Page 30: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 30

Inheritance

• Inheritance is a way to form new classes using classes that have already been defined.

• The former, known as derived classes, take over (or inherit) attributes and behavior of the latter, which are referred to as base classes.

• It is intended to help reuse of existing code with little or no modification.

Page 31: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 31

Inheritance

Accountacct_nonamebalancewithdraw()deposit( )

Accountacct_nonamebalancewithdraw()deposit( )

Savings Acc

interest

Savings Acc

interest

Current Acc

overdraft

Current Acc

overdraft

Page 32: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 32

Polymorphism

• It is using the same name to invoke different operations on objects of different data types.

• Idea of allowing the same code to be used with different types, resulting in more general and abstract implementations.

• It refers to the ability of an object to behave in different ways based on the context.

• Single message interpreted by different objects in different way.

Page 33: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 33

C++: The History

• Bjarne Stroustrup developed C++ (originally named "C with Classes") during the 1980s.

• The name C++ was coined by Rick Mascitti in 1983.

• Standard was ratified in 1998 as ISO/IEC 14882:1998

• New version of the standard (known informally as C++0x) is being developed.

Page 34: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 34

Attributes of Class

Member variables: State or properties of an object of that class.

Various variables that are defined in the class They are attributes of an object.

class Point { … … ;};class StraightLine {

// object’s attributesPoint &StartPoint, &Endpoint; //Reference data memberint Color; //Non-static data memberconst int Thickness; //Constant data member

// class’ attributesstatic int NoOfLineObjects; //Static data member

};

Page 35: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 35

Attributes of Class

Member functions: They are actions that object can do.

Used to access data inside the class. They are handles to the outside world and other objects.

Constructors - memory allocation, initialization for dataDestructors - freeing the memoryStatic functions - class oriented, modify only static dataNon-static ” - object oriented Const functions - cannot modify data member’s valuesVirtual functions - help dynamic binding of function calls to

implementation

Page 36: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 36

Attributes of Class

Access modifiers: Members can be declared

Privatevisible only inside the class

Protectedprivate + visible to the immediately derived

class Public

globally visible

Page 37: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 37

Attributes of Class

Scope Resolution Operator ( :: )

Unary scope resolution operatorHidden global variables can be accessedHidden local variables cannot be accessed

int a=10;void main () {

int a=20;{

int a=30;cout<<”local a=”<< a; //30cout<<”hidden global a=”<< ::a; //10;

}cout<<“hidden local a=“<<a; //20;

}

Page 38: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 38

Attributes of Class

Binary scope resolution operator

class HelloWorldCls {public: void displayHelloWorld();

};void HelloWorldCls :: displayHelloWorld() // Binary{ cout<<” This is member function”; }

void displayHelloWorld() // global function{ cout<<”This is global function”; }

void main(void){ HelloWorldCls hwObj;

hwObj.displayHelloWorld( ); // Member function calldisplayHelloWorld( ); // Global function call

}

Page 39: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 39

OOP Concepts: Summary

• In an object –oriented environment, software is a collection of discrete objects that encapsulate their data as well as the functionality to model real-world objects.

• Object orientation mainly Promotes of reusability.

• The main advantage of an OO system is that the class tree is dynamic and can grow.

• Data abstraction is the enforcement of a clear separation between the abstract properties of a data type and the concrete details of its implementation.

Page 40: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 40

Functions in C++

• References• Function Overloading• Default values • Inline Functions• Function Templates• Friend Functions• Static Members and Functions• Constant Functions and Constant data members

Page 41: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 41

• Call by Value: void swap (int, int); //prototypemain( ){

int x=4,y=5; cout<<“x=“<<x<<“ y=“<<y; output: x=4 y=5swap (x, y); //x, y actual argscout<<“x=“<<x<<“ y=“<<y; output: x=4 y=5

}void swap (int a, int b) //a, b formal args{

int k;k=a; a=b; b=k;

}

Parameter passing mechanisms

Page 42: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 42

• Call by value: another example

main( ){

int x,y; //actual argsvoid change(int,int);x=4; y=5;change(x, y);

}

void change(int a, int b){ //a,b formal args

int k;k=a; a=b; b=k;

}

4

x

5

y

5

a

4

b

Parameter passing mechanisms

Page 43: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 43

• Call by Address: void swap (int*, int*); //prototypemain( ){

int x=4,y=5; cout<<“x=“<<x<<“ y=“<<y; output: x=4 y=5swap (&x, &y); cout<<“x=“<<x<<“ y=“<<y; output: x=5 y=4

}void swap (int* a, int* b) {

int k;k=*a; *a=*b; *b=k;

}

Parameter passing mechanisms

Page 44: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 44

• Call by address: another example

main( ){

int x,y; //actual argsvoid change(int *,int*);x=4; y=5;change(&x, &y);

}

void change(int *a, int *b){ //a,b formal args

int *k;*k=*a; *a=*b; *b=*k;

}

4

x

5

y

After c

alling

chan

ge( )

X=5

y=4

Parameter passing mechanisms

Page 45: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 45

• Call by Reference: void swap (int&, int&); //prototypemain( ){

int x=4,y=5; cout<<“x=“<<x<<“ y=“<<y; output: x=4 y=5swap (x, y); cout<<“x=“<<x<<“ y=“<<y; output: x=5 y=4

}void swap (int &a, int &b) {

int k;k=a; a=b; b=k;

}

Parameter passing mechanisms

Page 46: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 46

• Not a copy of the variable and cannot exist without a variable to refer to it.

• Cannot be manipulated independently.• Can be viewed as pointers without dereferencing

notation.

References

Const pointer – Initialized to actualintcannot point to another variable

int actualint = 123;int *const intptr = &actualint;

Page 47: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 47

• Value of a reference cannot be changed

int actualint = 123;int &otherint = actualint;

123

actualint otherint

otherint++124

otherint++

References & Constants

int & const otherint = actualint; // Error

Meaningless as all references are constants by definition

Page 48: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 48

References

• Reference• Creates a alternate name or alias for the variable • Used to read or modify the original data stored in that

variable• Syntax of reference variable declaration:

DataType & ReferenceVariable = ValueVariable

Standard or user defined data type: char, short, int, float, etc.

Reference operator

C++ alias variable

C++ value variable

Page 49: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 49

References

int count = 1; // declare integer variable count

int &ref = count; // create ref as an alias for count

++ref; // increment count (using its alias)

int count = 1; // declare integer variable count

int &ref = count; // create ref as an alias for count

++ref; // increment count (using its alias)

count

ref

1

count

ref

2

Page 50: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 50

• Reference to a constant: Possible

• Constant reference declaration:

Not Possible

int actualint = 123;const int &otherint = actualint;

•readonly alias for actualint•can’t make any modification

int & const otherint = actualint;// Error

• Meaningless as all references are constants by definition

References and pointers

Page 51: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 51

Function Overloading

• Having more than one function with the same name differing in number of arguments or type of arguments.

• It is a kind of Compile time Polymorphism (dealt later)

Issues in Function Overloading• Functions differing in their return types only cannot

be overloaded.

Page 52: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 52

Function Overloading

• Passing constant values directly can also lead to ambiguity as internal type conversions may take place.

Consider: sum(int,int) and sum(float,float,float)

The compiler will not be able to distinguish between the two calls made below

sum(2,3) and sum(1.1, 2.2, 3.3)

Page 53: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 53

Example:

Convert function to convert a float Fahrenheit temperature to Celsius

• Prototype (Declaration):void ConvertFToC(float f, float &c);

• Definition:

void ConvertFToC(float f, float &c){    c = (f - 32.) * 5./9.;}

Function Overloading

Page 54: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 54

If Convert function is also needed to convert an integer Fahrenheit temperature to Celsius in the same program:

- give this function a new name, and update the name of the

"float" version as well.

void fConvertFToC(float f, float &c);void iConvertFToC(int f, int &c);

Function Overloading

Page 55: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 55

Function Overloading

• The compiler attempts to find an accurate function definition that matches in types and number of arguments and invokes the function.

• If no accurate match found, – compiler tries out implicit conversions.

E.g., char is converted to int, float to double etc.

Page 56: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 56

Default Values

• Function arguments assume default values, when their values are neglected or insufficient number of values are furnished during function calls.

• Can be constants, global variables, or function calls• Sets defaults in function prototype

int myFunction(int x = 1,int y = 2,int z = 3)myFunction(3)

x = 3, y and z get defaults (rightmost)myFunction(3, 5)

x = 3, y = 5 and z gets default

Page 57: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 57

• Examples:

// Declarations //Function calls

int add(int a, int b); // prototype 1int add(int a, int b, int c); // prototype 2double add(double x, double y) // prototype 3double add(int p, double q) // prototype 5double add(double p,int q) // prototype 5

cout<<add(15,10);cout<<add(15,10.5);cout<<add(15.5,10.5);cout<<add(15,10,5);cout<<add(0.15,1.05);

Default Values

Page 58: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 58

Default Values

Basic rules:• When a default is provided, all remaining

parameters must be given defaults.

• Default values must be of the correct type.

• Defaults can be placed on the function prototype or the function definition from right to left.

Page 59: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 59

Inline Functions

• Eliminates the function-call overhead (caused by jumping in and out of functions having few statements) involved in the conventional functioning approach.

– Keyword inline before function– Asks the compiler to copy code into program

instead of making function call– Compiler can ignore inline– Good for small, often-used functions

Page 60: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 60

Inline Functions

inline ReturnType FunctionName(Parameters) {

// Body of a main function}

Keyword, function qualifier

Syntax of inline function definition:

Page 61: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 61

• If a member function is implemented outside the class braces, it is not inline by default, but it can be defined as inline using the inline keyword.

inline int sqr(int num) { return num * num; }

void main( ){ ---

a=sqr(5);b=sqr(n);---

}

void main( ){ ---

a = 5 * 5;b = n * n;---

}

preprocessor

Inline Functions

Page 62: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 62

Inline Functions versus Macros

Inline functions: parsed by the compiler Macros : expanded by the preprocessor.

E.g., #define max(x,y) ((x>y)?x: y)

Limitation with macro:Macros are not functions and errors are not checked at compilation time.

Page 63: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 63

Reasons why Inline functions are better than macros:

• Follow all the protocols of type safety enforced on normal functions.

• Specified using the same syntax as any other function except that they include the inline keyword in the function declaration.

• Expressions passed as arguments to inline functions are evaluated once. In some cases, expressions passed as arguments to macros can be evaluated more than once.

Inline Functions versus Macros

Page 64: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 64

# define SQUARE(num) num * num

inline float square(float j){

return (j * j); }

void main( ){ int p=3,q=3,r,s;

r=SQUARE(++p);s=square(++q);cout<<“r = “ << r << “s = “<<s;

}

Output r =25 s =16

Macro SQUARE( ) expands into r = ++num * ++num

In macro expansion num is incremented twice.

Inline function square( ) var ‘q’ is incremented only

once and is assigned to jthen j * j.

Inline Functions versus Macros

Page 65: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 65

Static Data Members and Member Functions

• Static members are members that are single shared member common to all the objects created for a particular class.

• Memory allocation is done only once and not every time an object is created.

• Static functions can access only static variables

• Efficient when single copy of data is enough

• May seem like global variables, but have class scope

• Only accessible to objects of same class

Page 66: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 66

Static Members contd.,

• Static Data Members:

Object AObject A

Object BObject B

Object CObject C

Static variable

Page 67: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 67

• Static Member Example

class account { private: int currentBal; static int RateofInt;};myclass A(0), B(1);

currentBal=0currentBal=0Object AObject A

Object Object BB

Shared by Shared by all objectsall objects

RateofInt

Static Members contd.,

currentBal=1currentBal=1

Page 68: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 68

Static Members contd.,

• Static Data Members:class SavingsAccount{ private:

char name[30];float total;float CurrentRate;

public:SavingsAccount();void EarnInterest()

{total + = CurrentRate * total;}

}

Only one copy should be available as all objects should have same Interest rate

Declare CurrentRate as

static float CurrentRate;

To make CurrentRate accessible to all objects

Page 69: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 69

• A constant variable can be declared using const keyword

• Compiler error results if attempted to modify it

Syntax:const <variable-name> = <value>

Example: const int age = 20;const int age; // Not valid

Constant data member and Constant Functions

Page 70: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 70

• The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.

• Declaring a member function with the const keyword specifies that the function is a "read-only" function that does not modify the object for which it is called.

• If a const function attempt to change the data, the compiler will generate an error message.

int main(){ const int i = 5;

--- }

Constant data member and Constant Functions

Page 71: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 71

• Illegal to declare a const member function that modifies a data member

• For built-in types it doesn’t matter whether we return by value as a const

int fun1( ) {return 1;}int fun2( ) const {return 1;}main( ){ const int i = fun1( ); int j = fun2( );

--- }

int fun1( ) {return 1;}int fun2( ) const {return 1;}main( ){ const int i = fun1( ); int j = fun2( );

--- }

Constant data member and Constant Functions

Page 72: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 72

class Time{

int hour;public:

Time(int k) { hour=k; }void update( ) { hour++; }int value( ) const { return hour; }void cheat( ) const { hour++; }

};void main (void){

Time t(10);cout<<t.value( );

}

class Time{

int hour;public:

Time(int k) { hour=k; }void update( ) { hour++; }int value( ) const { return hour; }void cheat( ) const { hour++; }

};void main (void){

Time t(10);cout<<t.value( );

}

// error this is const

11

Constant data member and Constant Functions

Page 73: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 73

Function Templates

• To create generic functions that admit any data type as parameters and return a value without having to overload the function with all the possible data types.

• Until certain point they fulfill the functionality of a macro.

• Compact way to make overloaded functions

• Generate separate functions for different data types.

Page 74: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 74

template < class identifier > ReturnType FunctionName(arguments of type identifier)

Function Templates

template < class T > // or template< typename T >T square( T value1 ){

return value1 * value1;}

template < class T > // or template< typename T >T square( T value1 ){

return value1 * value1;}

Keyword for declaring function template

Keyword class

Name of the template data-type

Function parameters of type template, primitive or user-defined

Page 75: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 75

Examples:Convert function to convert a float Fahrenheit temperature to Celsius

Function Templates

Prototype (Declaration):

template <class Type>     void ConvertFToC(Type f, Type &c);

Definition:

template <class Type>     void ConvertFToC(Type f, Type &c){    c = (f - 32.) * 5./9.;}

Page 76: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 76

Function Templates

// definition of function template maximum

template < class T > // or template < typename T >

T maximum( T value1, T value2, T value3 ) {

T max = value1; if ( value2 > max )

max = value2; if ( value3 > max )

max = value3; return max;

}

maximum( int1, int2, int3 )

maximum( double1, double2, double3 )

maximum( char1, char2, char3 )

In main( )

1, 2, 31.1 , 2.1, 1.8A, B,C

Input values

32.1C

OutputMaximum value

Page 77: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 77

Function Template Overloading

• Other function templates with same name– Different parameters

• Non-template functions with same name– Different function arguments

• Compiler performs matching process–Tries to find precise match of function name

and argument types–If fails, function template generates

function-template specialization with precise match

Page 78: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 78

3. Classes and Objects

Objective:

After completing this module, you will be able to understand,– Constructors– Destructors– Copy Constructors– Constant Object– Static Object– Friend Class– Template Class

Page 79: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 79

Constructors

Introduction:• Constructors are special member functions with the

same name as the class. • A constructor initializes each object when it is

created• They are commonly used to initialize the member

variables.

Page 80: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 80

Constructors contd.,

• Constructors do not return values.

• A constructor is called whenever an object is defined or dynamically allocated using the “new” operator

• If no constructor is explicitly written then a default is created (not in the case of const and reference data members).

Page 81: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 81

Constructors contd.,

class sum{ public:

int x, y;sum( );

};sum::sum(void) {

cout<<" Inside sum( )\n";x=2;y=4; // if not initialized garbage

}void main( ){

sum s;cout<<"Inside main( )\n";cout<<"x= " << s.x<<"y= "<<s.y;

}

class sum{ public:

int x, y;sum( );

};sum::sum(void) {

cout<<" Inside sum( )\n";x=2;y=4; // if not initialized garbage

}void main( ){

sum s;cout<<"Inside main( )\n";cout<<"x= " << s.x<<"y= "<<s.y;

}

Inside sum( )Inside main( )x= 2 y= 4

Constructor declared

Object created and initialized by constructor

Constructor defined

Object s x= 2 y= 4

Page 82: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 82

Constructors with arguments

• Parameters can be passed to the constructorsclass sum{ public:

int x, y;sum(int i,int j);

};sum::sum(int i,int j) {

x=i;y=j;}void main( ){

sum s1(10,20);sum s2 = sum(30,40);cout<<"x= " << s1.x<<"y= "<<s1.y;cout<<"x= " << s2.x<<"y= "<<s2.y;

}

class sum{ public:

int x, y;sum(int i,int j);

};sum::sum(int i,int j) {

x=i;y=j;}void main( ){

sum s1(10,20);sum s2 = sum(30,40);cout<<"x= " << s1.x<<"y= "<<s1.y;cout<<"x= " << s2.x<<"y= "<<s2.y;

}

x= 10 y= 20

Parameterized Constructor

Object s1

Object s2 x= 30 y= 40

Constructor called implicitly

Page 83: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 83

Overloading Constructors

• Overloading Constructors - Multiple constructors declared in a class

• All constructors have different number of arguments • Depending on the number of arguments, compiler

executes corresponding constructor

sum( ) {x=10;y=20;};

sum(int, int) {x=i;y=j;};

sum(sum & i) {x=i.x;y=i.y;};

Two arguments

Copy constructor

No arguments

Page 84: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 84

Constructors with default arguments

• Constructors can be defined with default arguments

class sum{ public: int x, y;

sum(int i, int j=10);};sum::sum(int i,int j){x=i;y=j;}void main(){

sum s1(1),s2(8,9);cout<<"\nx in s1= " << s1.x<<"y in s1= "<<s1.y;cout<<"\nx in s2= " << s2.x<<"y in s2= "<<s2.y;

}

class sum{ public: int x, y;

sum(int i, int j=10);};sum::sum(int i,int j){x=i;y=j;}void main(){

sum s1(1),s2(8,9);cout<<"\nx in s1= " << s1.x<<"y in s1= "<<s1.y;cout<<"\nx in s2= " << s2.x<<"y in s2= "<<s2.y;

}

x= 1 y= 10Object s1

Object s2 x= 8 y= 9

Default value for j=10 (Used by the object s1)

Page 85: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 85

Copy Constructors

• C++ calls a copy constructor to make a copy of an object. • If there is no copy constructor defined for the class, C++ uses

the default copy constructor which copies each field, ie, makes a shallow copy.

• Constructors can accept arguments of any data type including user defined data types and an object of its own class

sum s1(10); //Object created and initialized

sum s2(s1); //Copy constructor

sum s3=s1; //Copy constructor

sum s4;

s4=s1; //Assignment

Page 86: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 86

Copy Constructors contd.,

class sum{ public:

int x;sum(){ }sum(int i) {x=i;}sum(sum &j) {x=j.x;}

};

class sum{ public:

int x;sum(){ }sum(int i) {x=i;}sum(sum &j) {x=j.x;}

};

void main(){

sum s1(10);sum s2(s1);sum s3=s1;sum s4;s4=s1;cout<<"\nx in s1= " << s1.x;cout<<"\nx in s2= " << s2.x;cout<<"\nx in s3= " << s3.x;cout<<"\nx in s4= " << s4.x;

}

void main(){

sum s1(10);sum s2(s1);sum s3=s1;sum s4;s4=s1;cout<<"\nx in s1= " << s1.x;cout<<"\nx in s2= " << s2.x;cout<<"\nx in s3= " << s3.x;cout<<"\nx in s4= " << s4.x;

}

Objects

x=10 x=10x=10 x=10

s1 s2 s3 s4

Page 87: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 87

#include<string.h>class String{ char* data; public: String(const char* s = "") { data = new char[20]; strcpy(data,s); } ~String() {delete [] data;} int size() const {return strlen(data);} void assign(char str*) { strcpy(data,str); void display() { cout << data; }};

#include<string.h>class String{ char* data; public: String(const char* s = "") { data = new char[20]; strcpy(data,s); } ~String() {delete [] data;} int size() const {return strlen(data);} void assign(char str*) { strcpy(data,str); void display() { cout << data; }};

int main(){ String s = "hello"; // same as String s("hello"); cout <<”s=”<<s.display( ); String empty; cout<<”empty=”<<empty.display();}

s = helloempty=

s = helloempty=

Copy Constructors contd.,

Page 88: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 88

int main(){ String s = "hello"; String t = s; // same as String t(s); s.display( ); t.display( ); t.assign(“world”); s.display( ); t.display( );}

int main(){ String s = "hello"; String t = s; // same as String t(s); s.display( ); t.display( ); t.assign(“world”); s.display( ); t.display( );}

hellohelloworldworld

hellohelloworldworld

hello\0

data

data

Copy Constructors contd.,

Shallow Copy

Page 89: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 89

String(const String& s){ data = new char[strlen(s.data)+1]; strcpy(data, s.data);}

String(const String& s){ data = new char[strlen(s.data)+1]; strcpy(data, s.data);} Deep Copy

Deep copy

hello\0data

datahello\0

Copy Constructors contd.,

Page 90: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 90

Destructors

• When an object goes out of scope then it is automatically destructed.

• It performs clean up of the object ( in the case of allocating memory inside the object using new )

• Destructors have no arguments and thus cannot be overloaded

Page 91: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 91

Destructors contd.,

Declaration– Same name as class

• Preceded with tilde (~)

~sum( ) { }~sum( ) { }

Page 92: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 92

Constant Objects

const objects using const keyword before object declaration.

For example:

const sample s ( m, n); // object s is constant

Page 93: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 93

Static Object

• When an object is created as static, the lifetime of the object will exist throughout the program

• Execution and scope of the instance will also be maintained.

Page 94: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 94

Static Object Example

#include<iostream.h>class account{ int acc_no;

public:account(){cout<<"Account constructor"; }~account(){cout<<"Account desctructor"; }

};void create_stobj(){ account vip;}void main(void){

clrscr();account acc1;create_stobj();getch();

}

#include<iostream.h>class account{ int acc_no;

public:account(){cout<<"Account constructor"; }~account(){cout<<"Account desctructor"; }

};void create_stobj(){ account vip;}void main(void){

clrscr();account acc1;create_stobj();getch();

}

Account constructorAccount constructorAccount destructor

Account constructorAccount constructorAccount destructor

Account constructorAccount constructor

Account constructorAccount constructor

static account vip;

Page 95: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 95

Friend class

• Like friend function, there is also a provision in C++ for having friend classes.

• Here an entire class is declared as friend for another class.

• When a class is declared as friend, it means the members of the friend class have access to all the public and private members of the class in which the declaration was made.

Page 96: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 96

#include <iostream.h>

class two

{

int a,b;

public:

void let(int x, int y)

{ a=x; b=y; }

void print(void)

{cout<<"a="<<a<<" b="<<b; }

void assign(one x)

{

a=x.a1;

b=x.b1;

}

};

#include <iostream.h>

class two

{

int a,b;

public:

void let(int x, int y)

{ a=x; b=y; }

void print(void)

{cout<<"a="<<a<<" b="<<b; }

void assign(one x)

{

a=x.a1;

b=x.b1;

}

};

class one

int a1,b1;

public:

one(void)

{ a1=5, b1=10;}

friend class two;

};

void main(void)

{ one o1;

two t1;

t1.let(4,2);

t1.print();

t1.assign(o1);

t1.print();

}

class one

int a1,b1;

public:

one(void)

{ a1=5, b1=10;}

friend class two;

};

void main(void)

{ one o1;

two t1;

t1.let(4,2);

t1.print();

t1.assign(o1);

t1.print();

}

a = 4 b= 2a= 5 b=10

a = 4 b= 2a= 5 b=10

Friend class example

Page 97: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 97

Template class

#include<iostream.h>Template < class Image>Class generic{

Image t;public:void sum(Image x, Image y){ t= x+ y; }void print (void){ cout<< “ The sum is : “ << t <<”\n”; }

};main ( ){ generic <int> x;

generic <float> y;x.sum(5,1);x.print( );y.sum(2.2, 3.7);y.print( ); }

#include<iostream.h>Template < class Image>Class generic{

Image t;public:void sum(Image x, Image y){ t= x+ y; }void print (void){ cout<< “ The sum is : “ << t <<”\n”; }

};main ( ){ generic <int> x;

generic <float> y;x.sum(5,1);x.print( );y.sum(2.2, 3.7);y.print( ); }

The sum is : 5The sum is : 5.9

The sum is : 5The sum is : 5.9

Page 98: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 98

• By using the concepts of inheritance, it is possible to create a new class from an existing one and add new features to it.

• Inheritance provides a mechanism for class level Reusability.

• Semantically, inheritance denotes an “is-a” relationship.

4. Inheritance

Page 99: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 99

Inheritance

• Inheritance is the relationship between a class and one or more refined version of it.

• The class being refined is called the superclass or base class and each refined version is called a subclass or derived class.

• Attributes and operations common to a group of subclasses are attached to the superclass and shared by each subclass.

• Each subclass is said to inherit the features of its superclass.

Page 100: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 100

Inheritance

Student

Reg.No. CourseMarks

Student

Reg.No. CourseMarks

Teaching Staff

Edn.Qual.Designation

Specialization

Teaching Staff

Edn.Qual.Designation

Specialization

Person

NameSexAge

Person

NameSexAge

“Person” is a generalization of “Student”. “Student” is a specialization of “Person”.

Page 101: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 101

Defining Derived Class

• The general form of deriving a subclass from a base class is as follows

• The visibility-mode is optional. • It may be either private or public or protected, by default it is

private. • This visibility mode specifies how the features of base class

are visible to the derived class.

Class derived-class-name : visibility-mode base-class-name{ ……………… //

……………….// members of the derived class};

Class derived-class-name : visibility-mode base-class-name{ ……………… //

……………….// members of the derived class};

Page 102: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 102

Inheritance

Types of Inheritance• Inheritance are of the following types

• Simple or Single Inheritance• Multi level or Varied Inheritance• Multiple Inheritance• Hierarchical Inheritance• Hybrid Inheritance• Virtual Inheritance

Page 103: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 103

Simple or Single Inheritance

• This a process in which a sub class is derived from only one superclass.

• a Class Student is derived from a Class Person

Person

Student subclass(derived class)

superclass(base class) class Person

{ ….. };

class Student : public Person

{ ………… };

class Person

{ ….. };

class Student : public Person

{ ………… };

visibility mode

Page 104: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 104

Multilevel or Varied Inheritance

• The method of deriving a class from another derived class is known as Multiple or Varied Inheritance.

• A derived class CS-Student is derived from another derived class Student.

Person

Student

CS -Student

Class Person{ ……};

Class Student : public Person { ……};Class CS -Student : public Student

{ …….};

Class Person{ ……};

Class Student : public Person { ……};Class CS -Student : public Student

{ …….};

Page 105: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 105

Multiple Inheritance

• A class is inheriting features from more than one super class

• Class Part-time Student is derived from two base classes, Employee and Student

Employee Student

Part-time Student

Class Employee{……..};

Class Student{……..};

Class Part-time Student : public Employee, public Student

{…….};

Class Employee{……..};

Class Student{……..};

Class Part-time Student : public Employee, public Student

{…….};

Page 106: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 106

Hierarchical Inheritance

• Many sub classes are derived from a single base class

• The two derived classes namely Student and Employee are derived from a base class Person.

Person

Student Employee

Class Person{……};

Class Student : public Person{……};

Class Employee : public Person

{……};

Class Person{……};

Class Student : public Person{……};

Class Employee : public Person

{……};

Page 107: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 107

Hybrid Inheritance

• In this type, more than one type of inheritance are used to derive a new sub class

• Multiple and multilevel type of inheritances are used to derive a class PG-Student

Person

Student

PG - Student

Gate Score

Class Person{ ……};

Class Student : public Person { ……};Class Gate Score

{…….};Class PG - Student : public Student

public Gate Score{………};

Class Person{ ……};

Class Student : public Person { ……};Class Gate Score

{…….};Class PG - Student : public Student

public Gate Score{………};

Page 108: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 108

Virtual Inheritance

• A sub class is derived from two super classes which in-turn have been derived from another class.

• The class Part-Time Student is derived from two super classes namely, Student and Employee.

• These classes in-turn derived from a common super class Person.

• The class Part-time Student inherits, the features of Person Class via two separate paths

Page 109: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 109

Person

Student Employee

Part-time Student

Virtual Inheritance

Class Person{……};

Class Student : public Person{……};

Class Employee : public Person {……};

Class Part-time Student : public Student, public Employee

{…….};

Class Person{……};

Class Student : public Person{……};

Class Employee : public Person {……};

Class Part-time Student : public Student, public Employee

{…….};

Page 110: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 110

Inheritance cont’d…,

Four things you might find in an Inheritance Hierarchy– Super class is too general to declare all behavior, so each

subclass adds its own behavior.– Super class legislates an abstract behavior and therefore

delegates implementation to sub class.– Super class specifies behavior, subclasses inherit

behavior.– Super class specifies behavior, subclasses choose to

override behavior.

Page 111: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 111

Access Control

• A member of a class can be private, public. In inheritance, we are going to use another access specify namely protected. So, a member of a class can be private, protected, or public.

• If a member of a class is private, its name can be used only by member functions and friends of the class in which it is declared.

• If it is protected, its name can be used only by member functions and friends of the class in which it is declared and by member functions and friends of classes derived from this class.

• If it is public, its name can be used by any function.

Page 112: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 112

Access Specifiers with Inheritance

• If we want an instance variable to be available for subclasses to change it, then we can choose access specifier protected.

• The following example illustrates the usage of these access specifiers.

Page 113: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 113

Access Specifiers with Inheritance

Class X { int priv; protected:

int prot; public:

int publ;void m( );

};void X::m( ){

priv =1; //Ok prot =1; //Ok publ =1; //Ok

} class Y : public X{ void mderived( ); }

Y::mderived( ){ priv =1; //Error priv is private and

//cannot be inherited prot =2; // Ok publ=3; // Ok }void global_fun(Y *p){

p->priv = 1; //Error : priv is //private of X

p->prot = 2; //Error : prot is //protected and the function global_fun( ) // is not a friend or a member of X or Y

p->publ =3; // Ok}

Page 114: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 114

Public, Protected and Private derivation

private : int a1;

protected : int a2;

public : int a3;

private : int b1;

protected : int b2;

public : int b3;

private : int b1;

protected: int a2; int b2

public:int b3;int a3;

Public Derivation

Class A Class B Class B: Public A

Page 115: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 115

Public derivation - example

class A {

private : int a; protected: int b; public : void get_a( ) { cin>>a;} void get_b( ) { cin>>b;} void print_a( ) { cout<<a;}

void print_b( ) {cout<<b;} }; class B : public A{

private : int c; protected: int d; public : void get_c( ) { cin>>c;} void get_d( ) {cin >>d;} void get_all( ) { get_a( ); cin>>b>>c>>d;} void print_cd( ){ cout<<c<<d;} void print_all( ) { print_a( ); cout<<b<<c<<d; } };

void main( ) { B b1; b1.get_a( ); b1.get_b( );

b1.get_c( );b1.get_d( );

b1.print_all( ); }

Page 116: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 116

Protected derivation - example

private : int a1;

protected : int a2;

public : int a3;

private : int b1;

protected : int b2;

public : int b3;

private : int b1;

protected:int a2; int b2,a3;

public:int b3;

Protected Derivation

• The inherited public and protected members of a base class become protected members of the derived class

Class A Class B Class B : Protected A

Page 117: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 117

Protected derivation - example

class A{

private: int a;protected: int b;public : void get_a( ) { cin>>a;}void get_b( ) { cin>>b;}void print_a( ) { cout<<a;}void print_b( ) {cout<<b;}

};class B : protected A{ private : int c;

protected: int d;public : void get_c( ) { cin>>c;}void get_d( ) {cin >>d;} void get_ab( ) { get_a( ); get_b( );}void print_cd( ){ cout<<c<<d;}void print_all( ) { print_a( ); cout<<b<<c<<d;};

}

void main( ){ B b1; b1.get_a( ); //ERROR b1.get_b( ); //ERROR b1.get_ab( ); b1.get_c( ); b1.get_d( ); b1.print_all( );}

Page 118: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 118

Private derivation - example

The inherited public and protected members of a private derivation become private members of the derived class.

private : int a1;

protected : int a2;

public : int a3;

private : int b1;

protected : int b2;

public : int b3;

private :int b1; int a2,a3;

protected:int b2; public:int b3;

Private Derivation

Class A Class B Class B : private A

Page 119: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 119

Private derivation - example

class A{

private: int a;protected: int b;public : void get_a( ) { cin>>a;}void get_b( ) { cin>>b;}void print_a( ) { cout<<a;}void print_b( ) {cout<<b;}

};class B : private A{

private : int c;protected: int d;public : void get_c( ) { cin>>c;}void get_d( ) {cin >>d;} void get_ab( ) { get_a( ); get_b( );}void print_cd( ){ cout<<c<<d;}void print_abcd( ) { print_a( ); cout<<b<<c<<d; }

};

Class C : public B { public :

void get_all( ){ get_a( ); //ERROR

get_b( ); //ERROR

get_ab( ); //Okget_c( ); //Okget_d( ); //Ok }

void print_all( ) { print_a( ); //ERROR

print_b( ); //ERRORprint_cd( ); //Ok

print_abcd( ); //Ok } }; void main( ) { C c1; c1.get_a( ); //ERROR c1.get_b( ); //ERROR c1.get_c( ); // Ok c1.get_d( ); //Ok c1.getall( ); //Ok c1.print_all( ); //Ok }

Page 120: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 120

Derived Class Constructors

• A base class constructor is invoked(if any) , when a derived class object is created.

• If base class constructor contains default constructor, then the derived class constructor need not send arguments to base class constructors explicitly.

• If a derived class has constructor, but base class has no constructor, then the appropriate derived class constructor executed automatically whenever a derived class object is created.

Page 121: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 121

Derived Class Constructors

class B{ int x;

public : B( ) { cout<<”B::B( )

Fires…”<<endl;}};

class D : public B{ int y;

public : D( ) { cout<<”D::D( )

Fires…”<<endl;}};void main( ){ D d;}

B::B( ) Fires…D::D( ) Fires…

Page 122: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 122

Derived Class Constructors

class B{

int a;public : B( ) { a = 0; cout<<”B::B( ) Fires…”<<endl;}

B(int x) { a =x; cout<<”B::B(int) Fires…”<<endl;}};class D : public B{ int b;

public : D( ) { b =0; cout<<”D::D( ) Fires…”<<endl;}

D(int x) { b =x; cout<<”D::D(int) Fires…”<<endl;}D(int x, int y) : B(y){ b =x; cout<<”D::D(int, int) Fires…”<<endl;}

};void main( ){

D d; D d(10); D d(10, 20);

}

B::B( ) Fires…D::D( ) Fires…B::B( ) Fires…D::D(int) Fires…B::B(int) Fires…D::D(int, int) Fires…

Page 123: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 123

Derived Class Destructors

• Derived class destructors are called before base class destructors.

class B{ int x;

public : B( ) { cout<<”B Constructor Invoked…”<<endl;}~B( ) { cout<<”B Destructor Invoked …”<<endl;}

};class D : public B{ int y;

public : D( ) { cout<<”D Constructor Invoked …”<<endl;}

~ D( ) { cout<<”D Destructor Invoked…”<<endl;}};void main( ){ D d; }

B Constructor Invoked…D Constructor Invoked…D Destructor Invoked…B Destructor Invoked …

Page 124: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 124

Overriding Member Functions

• When the same function exists in both the base class and the derived class, the function in the derived class is executed

class A {protected : int a;public : void getdata( ) { cin>>a;}void putdata( ) { cout << a;}};class B : public A{protected: int b;public : void getdata( ) { cin>>a>>b;}void putdata( ) { cout<<a<<b;} };

void main( ){

B b1; b1.getdata( ); // B::getdata( )

//is invokedb1.putdata( ); // B::putdata( )

//is invoked b1.A::getdata( ); // A::getdata( )

// is invoked b1.A::putdata( ); // A::putdata( )

//is invoked }

Page 125: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 125

Composition

class x { int i; public: x()

{i=0;} void set(int j)

{ i=j;} int read() const

{ return i;}};

class y{

int i; public: X x; Y() { i=0;} void f(intj)

{ i=j;} int g() const

{ return i;} };int main(){ Y y;

y.f(5);y.x.set(10);

}

• Classes having objects of other classes as their data members - composite classes

Page 126: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 126

SUMMARY

• A subclass may be derived from a class and inherit its methods and members.

• Different types are Single inheritance Multiple inheritance Multilevel inheritance

• Base class constructors are also executed whenever derived class objects created.

• Derived class can override a member function of a base class.

Page 127: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 127

5. Polymorphism

Introduction:In this Module one of the most important concept of OOPS i.e Polymorphism is discussed.

Objective: – After completing this module,you will be able to

understand, – Static Polymorphism– Overloaded Functions– Overloaded Operators– Dynamic Polymorphism– Virtual Functions

Page 128: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 128

Polymorphism

• Greek word meaning - many or multiple forms.

• In programming languages, polymorphism

means that some code or operations or objects behave differently in different contexts

• It provides a single interface to entities of different types.

Page 129: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 129

Types of polymorphism

Polymorphism

Operator Overloading

Function Overloading

Static Polymorphism

Dynamic Polymorphism

Virtual Fucntion

Page 130: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 130

Polymorphism

• Compiler determines a location in memory is called binding• Connecting a function call to a function body is called

Binding• The location may represent the following

– Variable names bound to their storage memory address (offset)

– Function names bound to their starting memory address (offset)

• Two kinds of binding • Compile-Time Binding • Run-Time Binding

Page 131: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 131

Static Polymorphism

• Compile-time binding or early binding is called as static polymorphism.

• Compile-Time Binding means– Compiler has enough information to determine an address

(offset) – Named variables have their addresses hard-coded during

compilation • Global variables are given offset from start of global

data area • Local variables are given offset from top of stack • Objects are given offset from start of object data

– executable code contains address references

Page 132: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 132

• To overload means give it an additional meaning.• Function definition syntax for operator overloading

Operator overloading

Page 133: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 133

Operator overloading

• A way of achieving static polymorphism is Operator overloading is just “syntactic sugar,” which means it is simply another way for you to make a function call

• Example: the + (plus) operator in C++ behaves differently depending on the operands:

4 + 5 - integer addition

3.14 + 2.0 - floating point addition

“sita” + "ram" - string concatenation• In C++, this is called operator overloading

Page 134: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 134

Operator Overloading

• Syntax of Operator overloading FRIEND function• Number of arguments in a friend function for

• Unary operator – 1• Binary operator – 2

ReturnType operator OperatorSymbol (argument list){

\\ Function body}

ReturnType operator OperatorSymbol (argument list){

\\ Function body}

Keyword Operator to be overloaded

Page 135: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 135

Operator Overloading

• Syntax of Operator overloading Class Member• Number of arguments in a member function for

• Unary operator – 0• Binary operator – 1

ReturnType classname :: OperatorSymbol (argument list){

\\ Function body}

ReturnType classname :: OperatorSymbol (argument list){

\\ Function body}

Operator to be overloaded

Page 136: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 136

• Operators that can not be overloaded

Operator Overloading

∙ ٫ → ?: sizeof

Operators that can be overloaded

+ - * / % ^ & |

~ ! = < > += -= *=

/= %= ^= &= |= << >> >>=

<<= == != <= >= && || ++

-- ->* , -> [] () new delete

new[] delete[]

Page 137: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 137

Unary Operators Overloading

• To declare a unary operator function as a nonstatic member

»return-type operatorop() • To declare a unary operator function as a global

function

»ret-type operatorop( arg )

Page 138: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 138

Unary Operators Overloading

class Point{public:  // Declare prefix and postfix increment operators.  Point& operator++(); // Prefix increment operator. This function can be used as lvalue.  Point operator++(int); // Postfix increment operator.  // Declare prefix and postfix decrement operators.  Point& operator--(); // Prefix decrement operator.  Point operator--(int); // Postfix decrement operator.  // Define default constructor.  Point() {x = y = 0; }  // Define accessor functions.  int x1() { return x; }  int y1() { return y; }private:  int x, y;};

class Point{public:  // Declare prefix and postfix increment operators.  Point& operator++(); // Prefix increment operator. This function can be used as lvalue.  Point operator++(int); // Postfix increment operator.  // Declare prefix and postfix decrement operators.  Point& operator--(); // Prefix decrement operator.  Point operator--(int); // Postfix decrement operator.  // Define default constructor.  Point() {x = y = 0; }  // Define accessor functions.  int x1() { return x; }  int y1() { return y; }private:  int x, y;};

Page 139: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 139

// Define prefix increment operator.Point& Point::operator++(){   x++;  y++;  return *this;}// Define postfix increment operator.Point Point::operator++(int){

  Point temp = *this;  ++*this;  return temp;

} // Define prefix decrement operator.Point& Point::operator--(){ x--;   y--;   return *this;}// Define postfix decrement operator.Point Point::operator--(int){ Point temp = *this;  --*this;  return temp;}

// Define prefix increment operator.Point& Point::operator++(){   x++;  y++;  return *this;}// Define postfix increment operator.Point Point::operator++(int){

  Point temp = *this;  ++*this;  return temp;

} // Define prefix decrement operator.Point& Point::operator--(){ x--;   y--;   return *this;}// Define postfix decrement operator.Point Point::operator--(int){ Point temp = *this;  --*this;  return temp;}

Unary Operators Overloading

Page 140: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 140

friend Point& operator++( Point& ) // Prefix incrementfriend Point& operator++( Point&, int ) // Postfix incrementfriend Point& operator--( Point& ) // Prefix decrementfriend Point& operator--( Point&, int ) // Postfix decrement

friend Point& operator++( Point& ) // Prefix incrementfriend Point& operator++( Point&, int ) // Postfix incrementfriend Point& operator--( Point& ) // Prefix decrementfriend Point& operator--( Point&, int ) // Postfix decrement

• The same operators can be defined in file scope (globally) using the following function heads:

Unary Operators Overloading

Page 141: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 141

Binary Operator Overloading

• To declare a binary operator function as a nonstatic member, you must declare it in the form:

»ret-type operatorop( arg )

• To declare a binary operator function as a global function, you must declare it in the form:

»ret-type operatorop( arg1, arg2 )

Page 142: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 142

Binary Operator Overloading

class Point { public: int x,y; Point () {}; Point (int,int); Point operator + (Point);};Point::Point (int a, int b) { x = a; y = b;}

Point Point::operator+ (Point P) { Point temp; temp.x = x + P.x; temp.y = y + P.y; return (temp);}

int main () { Point a (3,1); Point b (1,2); Point c; c = a + b; // c=a.operator+(b); cout << c.x << "," << c.y; return 0;}2,3

Page 143: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 143

Assignment operator overloading

• Assignment operator (=) is, strictly speaking, a binary operator. Its declaration is identical to any other binary operator,

Exceptions:• It must be a non-static member function. No operator = can

be declared as a non-member function. • It is not inherited by derived classes. • A default operator= function can be generated by the

compiler for class types if none exists (bitwise shallow copy)• User defined operator= function performs member wise deep

copy.

Page 144: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 144

class Point{ public: Point &operator=( Point & ); // Right side is the argument.

...};

// Define assignment operator.Point &Point::operator=( Point &pt){

x = pt. x; y = pt. y; return *this;

// Assignment operator returns left side.}

class Point{ public: Point &operator=( Point & ); // Right side is the argument.

...};

// Define assignment operator.Point &Point::operator=( Point &pt){

x = pt. x; y = pt. y; return *this;

// Assignment operator returns left side.}

Assignment operator overloading

Page 145: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 145

Overloading member function

class assign(){ int a; public:

operator + (assign var1);}; assign :: operator+ (assign var1)

{ a = 2 + var1.a; }assign object1,object2;main( ){

object1.a=5; object2.a = object2+ object1;cout<<“Object2.a is”<< object2.a<<“\n”;

}Object2.a is 7Object2.a is 7

Page 146: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 146

Overloading member function

class complex(){ double r,i; public:

complex(double re,double im):r(re),i(im) { }complex & operator + (complex & R);

};complex complex::operator+ (complex &R)

{ return (r+ R.r,i+R.i); }main( ){

Complex d(1.0,1.0);Complex b(1.0,1.0);Complex c(0.0,0.0);c=d.operator +(b);return 0;

}

//c=b+d

Page 147: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 147

• If you want the left-hand operand to be an object of some user defined class or predefined data types (This is when the operators << and >> are overloaded for iostreams) you should use a non member function

Non-member operators

Page 148: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 148

Non-member operators

friend Point operator+(int a, Point P) // for the expression P1 = 7 + P2 in main prg{

Point P1;P1.x = a + P.x;P1.y = a + P.y;return P1;

}ostream& operator<<(ostream& os, const Point& a) { os << a.x;

os << a.y; return os;

}istream& operator>>(istream& is, Point& a){ is >> a.x;

is >> a.y; return is;

}

Page 149: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 149

Type Conversion

• Objects of a given class type can be converted to objects of another type

• This is done by constructing an object of the target class type from the source class type and copying the result to the target object. This process is called conversion by constructor

• Objects can also be converted by user-supplied conversion functions Conversion

requiredConversion takes

palce inSource class

Conversion takes palce in

Destination class

Basic class Not applicable Constructor

Class basic Casting Operator Not Applicable

Class class Casting operator Constructor

Page 150: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 150

// spec1_conversion_functions2.cpp// C2666 expected#include <string.h>class String{public: // Define constructor that converts //from type char * String( char *s ) { strcpy( _text, s ); } // Define operator conversion function //to type char * operator char *()

{ return _text; } int operator==( const String &s ) { return !strcmp( _text, s._text ); }private: char _text[80];};

int main(){ String s( "abcd" ); char *ch = "efgh"; // Cause the compiler to //select a conversion. return s == ch;}

Type Conversion

The compiler has two choices and no way of determining which is correct. (i)It can convert ch to an object of type String using the constructor and then perform the comparison using the user-defined operator==. (ii)It can convert s to a pointer of type char * using the conversion function and then perform a comparison of the pointers.

Page 151: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 151

Restriction on using overloaded operators• You cannot define new operators, such as **. • You cannot redefine the meaning of operators when

applied to built-in data types. • Overloaded operators must either be a non-static

class member function or a global function. • Operators obey the precedence, grouping, and

number of operands dictated by their typical use with built-in types.

• If an operator can be used as either a unary or a binary operator (&, *, +, and -), you can overload each use separately.

Operator Overloading

Page 152: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 152

• Unary operators declared as member functions take no arguments; if declared as global functions, they take one argument.

• Binary operators declared as member functions take one argument; if declared as global functions, they take two arguments.

• Overloaded operators cannot have default arguments. • All overloaded operators except assignment (operator=) are

inherited by derived classes. • The first argument for member-function overloaded

operators is always of the class type of the object for which the operator is invoked No conversions are supplied for the first argument.

Operator Overloading

Page 153: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 153

Polymorphism : Non–Virtual Functions

class B{public: void f();

};class D: public B{

public:// f() not

overridden};void main(){

D dB*bp=&d;D*pd=&d;d.f(); // B::f()pb->f(); //B::f()pd->f(); // B::f()

}

No matters style of call, function name and object type serve as basics for function body selection.

All three calls of f( ) on derived class object d through the object, through a base class pointer and through a derived class pointer provides the same result.

Page 154: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 154

Polymorphism : Virtual functions

Virtual Functions• A member function that is declared as virtual in a base class

and redefined by a derived class.

• A virtual function defines a general class of actions . The redefined virtual function implements a specific method.

• For non-virtual functions with the same name, the system determines at compile time which of the function to invoke.

• For virtual methods with the same name the system determines at run time which of the methods to invoke.

Page 155: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 155

Virtual Functions : Example 1

• A virtual function is a member function that you expect to be redefined in derived class.

• A class member function can be made virtual by declaring it with the virtual keyword in the base class.

class One

{

public:

void whoami()

{

cout<<”One”<<endl;

}};

Page 156: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 156

Virtual Functions : Example 1 contd…

class Two : public One{

public:void whoami() {

cout<<”Two”<<endl; }};

class Three : public Two{

public:void whoami() {

cout<<”Three”<<endl; }

};

Page 157: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 157

Virtual Functions : Example 1 contd…

int main(){

One one ;Two two;Three three;One * array[3];array[0]=&one;array[1]=&two;array[2]=&three;for(int i=0;i<3;i++)array[i]->whoami();return EXIT_SUCCESS;

}

The Output is

One OneOne

Page 158: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 158

Virtual Functions : Binding

• In static binding the data type of the pointer resolves which method is invoked.

• It would be nice if the output were One, Two, Three.

• If whoami is made virtual, the system determines at runtime which of the three whoami to invoke.

• In dynamic binding , The type of the object pointed to resolve which method is invoked.

Page 159: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 159

Virtual Functions : Example 2

Class B {

int x;public:

virtual void g();

int h();};class D : public B{

int y;public:

void g();int h();

};

int main()

{

D d;

B *ptr = &d;

ptr->h(); B::h invoked

ptr->g(); D::h invoked

}

Page 160: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 160

Virtual Functions : Example 3

class Base { public:

virtual void fun(){cout<<”This is base fun().\n”;

}};class Derived0 : public Base{

public:void fun(){ cout<<” This is derived0 fun(). \n”;}

};class Derived1 : public Base{

public:void fun(){

cout<<” This is derived1 fun() . \n”;

}};

int main()

{

Base *ptr B;

Derived0 D0;

Derived1 D1;

ptr=&B;

ptr->fun();

ptr=&D0;

ptr->fun();

ptr=&D1;

p->fun();

return 0;

}

Page 161: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 161

Virtual Functions : Example 3 contd..

Output

This is base fun() This is derive0 fun()

This is derive1 fun()

Page 162: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 162

Virtual Functions : Constructors

• Virtual functions should be member functions.

• To construct an object , a constructor needs the exact type of the object it is to create.

• So a constructor can not be virtual but a destructor can be.

Page 163: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 163

Virtual Functions : Constructors contd…

class B {public: B( ) { this->f(); }

virtual void f() { cout<<”Executing B::f()”<<endln;

}};class D: public B {

public:D( ){ }virtual void f( ){

cout<<”Executing D::f()”<<endl;}

};

main(){

D d;cout<<”object d was created successfully”<<endl;d.f();

}

outputExecuting B::f()

object d created successfully.Executing D::f()

Page 164: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 164

Virtual Functions : Destructors

class B {

char * ptrB;

public:

B() {

ptrB=new char[5];

cout<<”B allocates 5 bytes”<<endl;

}

~B() {

delete []ptrB;

cout<<”B frees 5 bytes”<<endl;

}

};

Page 165: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 165

Virtual Functions : Destructors contd…

class D: public B {

char*ptrD;

public:

D( ) : B() {

ptrD=new char[1000];

cout<<”D allocates 1000 bytes”<<endl;

}

~D() {

delete[] ptrD;

cout<< “ D frees 1000 bytes “ << endl;

}

};

Page 166: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 166

Virtual Functions : Destructors contd…

int main(){

const int forever =1;

void f();

while(forever)

f();

return EXIT_SUCCESS;

}

void f(){

B*p=new D;

delete p;

}

The Memory will be exhausted, in each call of function f( ),

B allocates 5 bytesD allocates 1000 bytesB frees 5 bytes.

As p is of type B*, p is bound to B’s data members and methods, including constructors and destructors rather than to D’s methods . When f exits B::~B frees the 5 bytes. D::~D() fails to fire.

Page 167: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 167

Virtual Function : Default Arguments

class Base {public:

virtual int foo(int ival=1024){cout<<”base::foo()—ival :”<<ival <<endl;return ival;}};class Derived :: public Base{

public:virtual int foo(int ival=2048){ cout<<”derived::foo() –

ival :” << ival << endl; return ival;}

};

Page 168: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 168

Virtual Function : Default Arguments contd…

int main () {Derived *pd=new derived;Base *pb=pd;int val = pb->foo();cout<<”main : val through base “

<<val<<endl;val = pd->foo();cout<<”main : val through derived

“<<val<<endl;}

Outputderived:: foo() – ival : 1024main : val through base : 1024Derived :: foo() – ival : 2048main : val through derived : 2048

The default argument to be passed to foo() is not determined at run time, rather it is determined at compile time and is based on the type of the object through which the function is being invoked.

Page 169: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 169

Abstract Class & Pure Virtual Functions

Abstract Class

– A class that serves only as a base class from which other classes can be derived ;

– no instance of an abstract base class are ever created. – If a base class declares a pure virtual functions , no instance of the

class can be created, and so it is necessarily an abstract base class.

Pure Virtual Functions

– A virtual function that is declared in a base but not defined there ; – responsibility for defining the function falls on the derived classes,

each of which generally provides a different definition.

Page 170: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 170

Pure Virtual Function

class Base {

public:

virtual void show()=0

// Pure Virtual function

};

class Derv1 : public Base {

public:

void show(){

cout<<”\n Derv 1”; }

};

class Derv2 : public Base{public: void show(){cout<<”\n In Derv2”;}};

void main(){Base *List[2];Derv1 dv1;Derv2 dv2;List[0]=&dv1;List[1]=&dv2;List[0]->show();List[1]->show();}

Page 171: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 171

Virtual Function & Private/Protected Derivation

Polymorphism does not work with private or protected derivation

class Base{public:virtual void f();};class Derived : private Base{public:void f();};Base *ptr, b;Derived d;ptr=&d; // illegalptr=&b; // okptr->f(); // calls B::f()

Standard conversions don’t convert derived class pointers to base class pointers with private/protected derivation. Always use public inheritance with polymorphism.

Page 172: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 172

Virtual Function Implementation

• Most compiler build a virtual function table for each polymorphic class. All object of the same class share the same virtual function table(vtable).

• The vtable is an array of pointers to virtual functions that have definitions in either a base class or a derived class .

• The value of the pointer depends on whether or not the derives class override a base class virtual function with a new version of its own.

• A polymorphic class with at least one virtual function includes a hidden pointer (vptr) to its object which points to vtable.

Page 173: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 173

Virtual Function Implementation contd…

Base Members

vptr

Base b1;

Derived d1;

Base Members

vptr

Derived Members

Base vtbl;

Derived vtbl;

Base::f1()

Base::f2()

Base::f3()

Base::f1()

Derived::f2()

Base::f3()

Derived::f4()

Page 174: 1 ©Copyright 2004, Cognizant Academy, All Rights Reserved OBJECT ORIENTED PROGRAMMING INTRODUCTION

©Copyright 2004, Cognizant Academy, All Rights Reserved 174

Virtual Function – Example 4

class Base{

public :

Base() { }

virtual void f1() { cout<<”base::f1( )” << endl; }

virtual void f2( ) { cout << Base:: f2()”<<endl; }

virtual void f3() { cout<<”Base :: f3()”<<endl; }

};

class Derived {

public:

Derived() { }

void f2() { cout<<”Derived ::f2()”<<endl; }

virtual void f4() { cout<<Derived ::f4()”<,endl;}

};

Base b1;

Derived d1;

Base *p=&d1;

p->f4(); // illegal

Derived *q=&d1;

q->f4() ;// legal

With the help of base class pointer, we can’t access any derived class members.