Object Oriented Programming Presentation

  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Object Oriented Programming Presentation as PDF for free.

More details

  • Words: 11,426
  • Pages: 178
Object Oriented Programming

Knowledge Level: Basic

About the Author Created By:

Cognizant Academy

Version and Date:

OOPSCONCPT/PPT/0404/1.0

©Copyright 2004, Cognizant Academy, All Rights Reserved

2

Courseware Information Course Description

•After completing this course, you will be able to understand the importance of OOPS in programming paradigm •Basic Terminology’s involved into OOPS.

Level

Basic

Prerequisites

A participant must know basic understanding of programming to do this course

©Copyright 2004, Cognizant Academy, All Rights Reserved

3

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: 1 Programming paradigms

2 OOPS Concepts

5 Inheritance

3 Functions in C++

4 Classes and Objects

6 Polymorphism

©Copyright 2004, Cognizant Academy, All Rights Reserved

4

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. ©Copyright 2004, Cognizant Academy, All Rights Reserved

5

Programming Paradigms : Overview 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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

6

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

©Copyright 2004, Cognizant Academy, All Rights Reserved

7

Procedural Programming • 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) Global data

Sub-programs ©Copyright 2004, Cognizant Academy, All Rights Reserved

8

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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

9

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. Global data

Local Data

Local Data

Local Data

Sub-programs

Modules ©Copyright 2004, Cognizant Academy, All Rights Reserved

10

Structured Programming • Three types of control flow are used: - sequence

- selection Y/N

- iteration

©Copyright 2004, Cognizant Academy, All Rights Reserved

11

Structured Programming • 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

©Copyright 2004, Cognizant Academy, All Rights Reserved

12

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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

13

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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

14

Object Oriented Programming  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 B

Data variable Object A

Object C

Member Function Data variable

Data variable

Member Function

Member Function

©Copyright 2004, Cognizant Academy, All Rights Reserved

15

Object Oriented Programming • Does not deal with programming in the sense of developing algorithms or data-structures • Focuses on ADT

©Copyright 2004, Cognizant Academy, All Rights Reserved

16

POA Vs OOA Procedure Oriented Approach: Director Cell

System assembled with the supplied H/w components

Fetch Components

H/W Components Room

Send H/w + Instructions to assemble the system

©Copyright 2004, Cognizant Academy, All Rights Reserved

Service Engineer Room

17

Object Oriented Approach:

©Copyright 2004, Cognizant Academy, All Rights Reserved

18

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)

©Copyright 2004, Cognizant Academy, All Rights Reserved

19

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. ©Copyright 2004, Cognizant Academy, All Rights Reserved

20

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

©Copyright 2004, Cognizant Academy, All Rights Reserved

21

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. ©Copyright 2004, Cognizant Academy, All Rights Reserved

22

Class & Object Account acct_no name balance withdraw() deposit( )

Account:acct1

Account:acct2

431245 Patrick 50567.78

431246 Meyer 35567.78

©Copyright 2004, Cognizant Academy, All Rights Reserved

23

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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

24

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. ©Copyright 2004, Cognizant Academy, All Rights Reserved

25

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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

26

Abstraction "A view of a problem that extracts the essential information relevant to a particular purpose and ignores the remainder of the 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. ©Copyright 2004, Cognizant Academy, All Rights Reserved

27

Data Abstraction 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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

28

Data Abstraction 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. ©Copyright 2004, Cognizant Academy, All Rights Reserved

29

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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

30

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 )

©Copyright 2004, Cognizant Academy, All Rights Reserved

31

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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

32

Inheritance Account acct_no name balance withdraw() deposit( )

Savings Acc interest

©Copyright 2004, Cognizant Academy, All Rights Reserved

Current Acc overdraft

33

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. ©Copyright 2004, Cognizant Academy, All Rights Reserved

34

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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

35

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 attributes Point &StartPoint, &Endpoint; //Reference data member int Color; //Non-static data member const int Thickness; //Constant data member // class’ attributes static int NoOfLineObjects; //Static data member }; ©Copyright 2004, Cognizant Academy, All Rights Reserved

36

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 Destructors Static functions Non-static ” Const functions Virtual functions

- memory allocation, initialization for data - freeing the memory - class oriented, modify only static data - object oriented - cannot modify data member’s values - help dynamic binding of function calls to implementation

©Copyright 2004, Cognizant Academy, All Rights Reserved

37

Attributes of Class Access modifiers: Members can be declared  Private visible only inside the class  Protected private + visible to the immediately derived class  Public globally visible

©Copyright 2004, Cognizant Academy, All Rights Reserved

38

Attributes of Class Scope Resolution Operator ( :: ) Unary scope resolution operator Hidden global variables can be accessed Hidden local variables cannot be accessed int a=10; void main () { int a=20; { int a=30; cout<<”local a=”<< a; cout<<”hidden global a=”<< ::a; } cout<<“hidden local a=“<
//30 //10; //20; 39

Attributes of Class Binary scope resolution operator class HelloWorldCls { public: void displayHelloWorld(); }; void HelloWorldCls :: displayHelloWorld() { cout<<” This is member function”;

// Binary }

void displayHelloWorld() // global function { cout<<”This is global function”; } void main(void) { HelloWorldCls hwObj; hwObj.displayHelloWorld( ); displayHelloWorld( ); } ©Copyright 2004, Cognizant Academy, All Rights Reserved

// Member function call // Global function call 40

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. ©Copyright 2004, Cognizant Academy, All Rights Reserved

41

Functions in C++ • • • • • • • •

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

©Copyright 2004, Cognizant Academy, All Rights Reserved

42

Parameter passing mechanisms • Call by Value:

void swap (int, int); main( ) { int x=4,y=5; cout<<“x=“<<x<<“ y=“<
//prototype

output: x=4 y=5 //x, y actual args output: x=4 y=5 //a, b formal args

43

Parameter passing mechanisms • Call by value: another example main( ) { int x,y; //actual args void change(int,int); x=4; y=5; change(x, y);

x 4

y 5

a 5

b 4

}

void change(int a, int b) { //a,b formal args int k; k=a; a=b; b=k; } ©Copyright 2004, Cognizant Academy, All Rights Reserved

44

Parameter passing mechanisms • Call by Address:

void swap (int*, int*); main( ) { int x=4,y=5; cout<<“x=“<<x<<“ y=“<
//prototype

output: x=4 y=5 output: x=5 y=4

45

Parameter passing mechanisms • Call by address: another example main( ) { int x,y; //actual args void 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; } ©Copyright 2004, Cognizant Academy, All Rights Reserved

x 4 4 ge( = y an h c 5 g = n i X ll a c r tf e A

y 5 )

46

Parameter passing mechanisms • Call by Reference: void swap (int&, int&); main( ) { int x=4,y=5; cout<<“x=“<<x<<“ y=“<
//prototype

output: x=4 y=5 output: x=5 y=4

47

References • 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. int actualint = 123; int *const intptr = &actualint; Const pointer – Initialized to actualint cannot point to another variable ©Copyright 2004, Cognizant Academy, All Rights Reserved

48

References & Constants • Value of a reference cannot be changed int actualint = 123; int &otherint = actualint;

actualint

otherint++

int & const otherint = actualint;

// Error

otherint

123 124

otherint++

Meaningless as all references are constants by definition ©Copyright 2004, Cognizant Academy, All Rights Reserved

49

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: Standard or user defined data type: char, short, int, float, etc. Reference operator C++ alias variable C++ value variable

DataType & ReferenceVariable = ValueVariable ©Copyright 2004, Cognizant Academy, All Rights Reserved

50

References int count = 1; // declare integer variable count int &ref = count; // create ref as an alias for count ++ref; // increment count (using its alias)

count

count 1

ref

©Copyright 2004, Cognizant Academy, All Rights Reserved

2

ref

51

References and pointers • Reference to a constant: Possible

int actualint = 123; const int &otherint = actualint; •readonly alias for actualint •can’t make any modification

• Constant reference declaration: Not Possible

int & const otherint = actualint; // Error

• Meaningless as all references are constants by definition ©Copyright 2004, Cognizant Academy, All Rights Reserved

52

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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

53

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) ©Copyright 2004, Cognizant Academy, All Rights Reserved

54

Function Overloading 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.; } ©Copyright 2004, Cognizant Academy, All Rights Reserved

55

Function Overloading 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); ©Copyright 2004, Cognizant Academy, All Rights Reserved

56

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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

57

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

©Copyright 2004, Cognizant Academy, All Rights Reserved

58

Default Values • Examples: // Declarations int add(int a, int b); int add(int a, int b, int c); double add(double x, double y) double add(int p, double q) double add(double p,int q)

//Function calls // prototype 1 // prototype 2 // prototype 3 // prototype 5 // prototype 5

©Copyright 2004, Cognizant Academy, All Rights Reserved

cout<
59

Default Values Basic rules: • When a default is provided, all parameters must be given defaults.

remaining

• Default values must be of the correct type. • Defaults can be placed on the function prototype or the function definition from right to left.

©Copyright 2004, Cognizant Academy, All Rights Reserved

60

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

©Copyright 2004, Cognizant Academy, All Rights Reserved

61

Inline Functions Syntax of inline function definition: Keyword, function qualifier

inline ReturnType FunctionName(Parameters) { // Body of a main function }

©Copyright 2004, Cognizant Academy, All Rights Reserved

62

Inline Functions inline int sqr(int num) { return num * num; } void main( ) { --a=sqr(5); b=sqr(n); --}

preprocessor

void main( ) { --a = 5 * 5; b = n * n; --}

• 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. ©Copyright 2004, Cognizant Academy, All Rights Reserved

63

Inline Functions versus Macros Inline functions: parsed by the compiler Macros : expanded by the preprocessor. E.g., #define max(x,y) ((x rel="nofollow">y)?x: y) Limitation with macro: Macros are not functions and errors are not checked at compilation time.

©Copyright 2004, Cognizant Academy, All Rights Reserved

64

Inline Functions versus Macros 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. ©Copyright 2004, Cognizant Academy, All Rights Reserved

65

Inline Functions versus Macros # 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; }

©Copyright 2004, Cognizant Academy, All Rights Reserved

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 j then j * j. 66

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 ©Copyright 2004, Cognizant Academy, All Rights Reserved

67

Static Members contd., • Static Data Members: Object A

Object B

Static variable

Object C

©Copyright 2004, Cognizant Academy, All Rights Reserved

68

Static Members contd., • Static Member Example class account { private: int currentBal; static int RateofInt; }; myclass A(0), B(1);

Shared by all objects Object B

Ra

te of In

t

Object A

currentBal=0

©Copyright 2004, Cognizant Academy, All Rights Reserved

currentBal=1 69

Static Members contd., • Static Data Members:

class SavingsAccount Only one copy should { be available as all private: objects should have char name[30]; same Interest rate float total; float CurrentRate; public: To make CurrentRate accessible to all objects SavingsAccount(); void EarnInterest() { Declare CurrentRate as total + = CurrentRate * total; static float CurrentRate; } } ©Copyright 2004, Cognizant Academy, All Rights Reserved

70

Constant data member and Constant Functions • A constant variable can be declared using const keyword • Compiler error results if attempted to modify it Syntax: const = Example: const int age = 20; const int age; // Not valid

©Copyright 2004, Cognizant Academy, All Rights Reserved

71

Constant data member and Constant Functions • The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. int main() { const int i = 5; --}

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

©Copyright 2004, Cognizant Academy, All Rights Reserved

72

Constant data member and Constant Functions • 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( ); --}

©Copyright 2004, Cognizant Academy, All Rights Reserved

73

Constant data member and Constant Functions 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<
©Copyright 2004, Cognizant Academy, All Rights Reserved

// error this is const

11

74

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. ©Copyright 2004, Cognizant Academy, All Rights Reserved

75

Function Templates Keyword for declaring function template Keyword class Name of the template data-type Function parameters of type template, primitive or user-defined

template < class identifier > ReturnType FunctionName(arguments of type identifier) template < class T > // or template< typename T > T square( T value1 ) { return value1 * value1; } ©Copyright 2004, Cognizant Academy, All Rights Reserved

76

Function Templates Examples: Convert function to convert a float Fahrenheit temperature to Celsius Prototype (Declaration): template void ConvertFToC(Type f, Type &c); Definition: template void ConvertFToC(Type f, Type &c) { c = (f - 32.) * 5./9.; } ©Copyright 2004, Cognizant Academy, All Rights Reserved

77

Function Templates

efinition of function template maximum

plate < class T > // or template < typename T > aximum( T value1, T value2, T value3 ) T max = value1; if ( value2 > max ) max = value2; if ( value3 > max ) max = value3; return max;

In main( ) maximum( int1, int2, int3 )

maximum( double1, double2, double3 )

maximum( char1, char2, char3 )

Input values 1, 2, 3 1.1 , 2.1, 1.8 A, B,C ©Copyright 2004, Cognizant Academy, All Rights Reserved

Output Maximum value 3 2.1 C 78

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 functiontemplate specialization with precise match ©Copyright 2004, Cognizant Academy, All Rights Reserved

79

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

©Copyright 2004, Cognizant Academy, All Rights Reserved

80

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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

81

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

©Copyright 2004, Cognizant Academy, All Rights Reserved

82

Constructors contd., class sum { public: int x, y;

sum( );

Constructor declared Constructor defined

};

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; } ©Copyright 2004, Cognizant Academy, All Rights Reserved

Object created and initialized by constructor Inside sum( ) Inside main( ) x= 2 y= 4

Object s x= 2 y= 4 83

Constructors with arguments • Parameters can be passed to the constructors class sum { public: int x, y;

Parameterized Constructor

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; } ©Copyright 2004, Cognizant Academy, All Rights Reserved

Constructor called implicitly

Object s1

x= 10 y= 20

Object s2

x= 30 y= 40 84

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

No arguments

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

Two arguments

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

Copy constructor

©Copyright 2004, Cognizant Academy, All Rights Reserved

85

Constructors with default arguments • Constructors can be defined with default arguments class sum Object s1 { public: int x, y; Object s2 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; } ©Copyright 2004, Cognizant Academy, All Rights Reserved

x= 1 y= 10 x= 8 y= 9 Default value for j=10 (Used by the object s1)

86

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 ©Copyright 2004, Cognizant Academy, All Rights Reserved

87

Copy Constructors contd., class sum { public: int x; sum(){ } sum(int i) {x=i;} sum(sum &j) {x=j.x;} };

Objects

s1 x=10

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; } s2 x=10

©Copyright 2004, Cognizant Academy, All Rights Reserved

s3

s4

x=10

x=10 88

Copy Constructors contd., #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(); }

©Copyright 2004, Cognizant Academy, All Rights Reserved

s = hello empty=

89

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

hello hello world world

Shallow Copy

data

hello\0 data

©Copyright 2004, Cognizant Academy, All Rights Reserved

90

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

data

Deep Copy

hello\0 Deep copy

data

©Copyright 2004, Cognizant Academy, All Rights Reserved

hello\0

91

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

©Copyright 2004, Cognizant Academy, All Rights Reserved

92

Destructors contd., Declaration – Same name as class • Preceded with tilde (~) ~sum( ) { }

©Copyright 2004, Cognizant Academy, All Rights Reserved

93

Constant Objects const objects using const keyword before object declaration.

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

©Copyright 2004, Cognizant Academy, All Rights Reserved

94

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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

95

Static Object Example #include class account { int acc_no; public: account() {cout<<"Account constructor"; } ~account() {cout<<"Account desctructor"; } }; void create_stobj() { account vip; } void main(void) sta tic { acc oun clrscr(); t vi account acc1; p; create_stobj(); getch(); } ©Copyright 2004, Cognizant Academy, All Rights Reserved

Account constructor Account constructor Account destructor

Account constructor Account constructor

96

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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

97

Friend class example #include class two { int a,b; public: void let(int x, int y) { a=x; b=y; void print(void) {cout<<"a="< 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 x; generic y; x.sum(5,1); The sum is : 5 x.print( ); The sum is : 5.9 y.sum(2.2, 3.7); y.print( ); }

©Copyright 2004, Cognizant Academy, All Rights Reserved

}

99

4. Inheritance • 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, relationship.

inheritance

©Copyright 2004, Cognizant Academy, All Rights Reserved

denotes

an

“is-a”

100

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. ©Copyright 2004, Cognizant Academy, All Rights Reserved

101

Inheritance Person Name Sex Age

Student

Teaching Staff

Reg.No. Course Marks

Edn.Qual. Designation Specialization

“Person” is a generalization of “Student”. “Student” is a specialization of “Person”. ©Copyright 2004, Cognizant Academy, All Rights Reserved

102

Defining Derived Class • The general form of deriving a subclass from a base class is as follows Class derived-class-name : visibility-mode base-class-name { ……………… // ……………….// members of the derived class };

• 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. ©Copyright 2004, Cognizant Academy, All Rights Reserved

103

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

©Copyright 2004, Cognizant Academy, All Rights Reserved

104

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 class Person

Person

superclass(base class) { …..

};

class Student : public Person {

Student

subclass(derived class)

………… };

visibility mode

©Copyright 2004, Cognizant Academy, All Rights Reserved

105

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 { …….};

©Copyright 2004, Cognizant Academy, All Rights Reserved

106

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 {…….};

©Copyright 2004, Cognizant Academy, All Rights Reserved

107

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 {……};

©Copyright 2004, Cognizant Academy, All Rights Reserved

108

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 {………};

©Copyright 2004, Cognizant Academy, All Rights Reserved

109

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

©Copyright 2004, Cognizant Academy, All Rights Reserved

110

Virtual Inheritance Person

Student

Employee

Part-time Student

Class Person {……}; Class Student : public Person {……}; Class Employee : public Person {……}; Class Part-time Student : public Student, public Employee {…….};

©Copyright 2004, Cognizant Academy, All Rights Reserved

111

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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

112

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. ©Copyright 2004, Cognizant Academy, All Rights Reserved

113

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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

114

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 } }

©Copyright 2004, Cognizant Academy, All Rights Reserved

115

Public, Protected and Private derivation

Class A

Class B

Class B: Public A

private : int a1;

private : int b1;

private : int b1;

protected : int a2;

protected : int b2;

protected: int a2; int b2

public : int a3;

public : int b3;

public: int b3;int a3;

Public Derivation ©Copyright 2004, Cognizant Academy, All Rights Reserved

116

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<>c;} void get_d( ) {cin >>d;} void get_all( ) { get_a( ); cin>>b>>c>>d;} void print_cd( ){ cout<
void main( ) { B b1; b1.get_a( ); b1.get_b( ); b1.get_c( ); b1.get_d( ); b1.print_all( ); }

117

Protected derivation - example • 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

private : int a1;

private : int b1;

private : int b1;

protected : int a2;

protected : int b2;

protected: int a2; int b2,a3;

public : int a3;

public : int b3;

public: int b3;

Protected Derivation ©Copyright 2004, Cognizant Academy, All Rights Reserved

118

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<>c;} void get_d( ) {cin >>d;} void get_ab( ) { get_a( ); get_b( );} void print_cd( ){ cout<
void main( ) { B b1; b1.get_a( ); //ERROR b1.get_b( ); //ERROR b1.get_ab( ); b1.get_c( ); b1.get_d( ); b1.print_all( ); }

119

Private derivation - example The inherited public and protected members of a private derivation become private members of the derived class. Class A

Class B

private : int a1;

private : int b1;

protected : int a2;

protected : int b2;

public : int a3;

public : int b3;

Class B : private A private : int b1; int a2,a3; protected: int b2; public: int b3;

Private Derivation ©Copyright 2004, Cognizant Academy, All Rights Reserved

120

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<>c;} void get_d( ) {cin >>d;} void get_ab( ) { get_a( ); get_b( );} void print_cd( ){ cout<
Class C : public B { public : void get_all( ) { get_a( ); //ERROR get_b( ); //ERROR get_ab( ); //Ok get_c( ); //Ok get_d( ); //Ok } void print_all( ) { print_a( ); //ERROR print_b( ); //ERROR print_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 } 121

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. ©Copyright 2004, Cognizant Academy, All Rights Reserved

122

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; } ©Copyright 2004, Cognizant Academy, All Rights Reserved

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

123

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); }

©Copyright 2004, Cognizant Academy, All Rights Reserved

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

124

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

©Copyright 2004, Cognizant Academy, All Rights Reserved

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

125

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<
©Copyright 2004, Cognizant Academy, All Rights Reserved

void main( ) { B b1; b1.getdata( );

// B::getdata( ) //is invoked b1.putdata( ); // B::putdata( ) //is invoked b1.A::getdata( ); // A::getdata( ) // is invoked b1.A::putdata( ); // A::putdata( ) //is invoked }

126

Composition • Classes having objects of other classes as their data members - composite classes class y { int i; public: class x { int i; public: x() {i=0;} void set(int j) { i=j;} int read() const { return i;} }; ©Copyright 2004, Cognizant Academy, All Rights Reserved

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); } 127

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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

128

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 ©Copyright 2004, Cognizant Academy, All Rights Reserved

129

Polymorphism • Greek word meaning forms.

many or multiple

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

©Copyright 2004, Cognizant Academy, All Rights Reserved

130

Types of polymorphism Polymorphism

Static Polymorphism

Function Overloading

Operator Overloading

©Copyright 2004, Cognizant Academy, All Rights Reserved

Dynamic Polymorphism

Virtual Fucntion

131

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 ©Copyright 2004, Cognizant Academy, All Rights Reserved

132

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 ©Copyright 2004, Cognizant Academy, All Rights Reserved

133

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

©Copyright 2004, Cognizant Academy, All Rights Reserved

134

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

©Copyright 2004, Cognizant Academy, All Rights Reserved

135

Operator Overloading • Syntax of Operator overloading FRIEND function • Number of arguments in a friend function for • Unary operator – 1 • Binary operator – 2 Keyword

Operator to be overloaded

ReturnType operator OperatorSymbol (argument list) { \\ Function body } ©Copyright 2004, Cognizant Academy, All Rights Reserved

136

Operator Overloading • Syntax of Operator overloading Class Member • Number of arguments in a member function for • Unary operator – 0 • Binary operator – 1 Operator to be overloaded ReturnType classname :: OperatorSymbol (argument list) { \\ Function body } ©Copyright 2004, Cognizant Academy, All Rights Reserved

137

Operator Overloading Operators that can be overloaded +

-

*

/

%

^

&

|

~

!

=

<

rel="nofollow">

+=

-=

*=

/=

%=

^=

&=

|=

<<

>>

>>=

<<=

==

!=

<=

>=

&&

||

++

--

->*

,

->

[]

()

new

delete

new[]

delete[]

• Operators that can not be overloaded



٫



©Copyright 2004, Cognizant Academy, All Rights Reserved

?:

sizeof 138

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 )

©Copyright 2004, Cognizant Academy, All Rights Reserved

139

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; }; ©Copyright 2004, Cognizant Academy, All Rights Reserved

140

Unary Operators Overloading // 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; } ©Copyright 2004, Cognizant Academy, All Rights Reserved

141

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

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

©Copyright 2004, Cognizant Academy, All Rights Reserved

142

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 )

©Copyright 2004, Cognizant Academy, All Rights Reserved

143

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; } 2,3

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

©Copyright 2004, Cognizant Academy, All Rights Reserved

144

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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

145

Assignment operator overloading 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.} ©Copyright 2004, Cognizant Academy, All Rights Reserved

146

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”; } ©Copyright 2004, Cognizant Academy, All Rights Reserved

Object2.a is 7

147

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; } ©Copyright 2004, Cognizant Academy, All Rights Reserved

//c=b+d 148

Non-member operators • 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

©Copyright 2004, Cognizant Academy, All Rights Reserved

149

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; } ©Copyright 2004, Cognizant Academy, All Rights Reserved

150

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 Conversion takes Conversion required

palce in Source class

takes palce in Destination class

Basic class

Not applicable

Constructor

Class basic

Casting Operator

Not Applicable

Class class

Casting operator

Constructor

©Copyright 2004, Cognizant Academy, All Rights Reserved

151

Type Conversion // 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; } 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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

152

Operator Overloading 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. ©Copyright 2004, Cognizant Academy, All Rights Reserved

153

Operator Overloading • 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. ©Copyright 2004, Cognizant Academy, All Rights Reserved

154

Polymorphism : Non–Virtual Functions class B{ public: void f(); }; class D: public B{ public: // f() not overridden }; void main(){ Dd B*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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

155

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. ©Copyright 2004, Cognizant Academy, All Rights Reserved

156

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; } }; ©Copyright 2004, Cognizant Academy, All Rights Reserved

157

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; } }; ©Copyright 2004, Cognizant Academy, All Rights Reserved

158

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 One One

} ©Copyright 2004, Cognizant Academy, All Rights Reserved

159

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. ©Copyright 2004, Cognizant Academy, All Rights Reserved

160

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 }

©Copyright 2004, Cognizant Academy, All Rights Reserved

161

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”; } }; ©Copyright 2004, Cognizant Academy, All Rights Reserved

int main() { Base *ptr B; Derived0 D0; Derived1 D1; ptr=&B; ptr->fun(); ptr=&D0; ptr->fun(); ptr=&D1; p->fun(); return 0; } 162

Virtual Functions : Example 3 contd..

Output This is base fun() This is derive0 fun() This is derive1 fun()

©Copyright 2004, Cognizant Academy, All Rights Reserved

163

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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

164

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; } }; ©Copyright 2004, Cognizant Academy, All Rights Reserved

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

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

165

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

©Copyright 2004, Cognizant Academy, All Rights Reserved

166

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

©Copyright 2004, Cognizant Academy, All Rights Reserved

167

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 bytes D allocates 1000 bytes B 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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

168

Virtual Function : Default Arguments class Base { public: virtual int foo(int ival=1024){ cout<<”base::foo()—ival :”<
169

Virtual Function : Default Arguments contd… int main () { Derived *pd=new derived; Base *pb=pd; int val = pb->foo(); cout<<”main : val through base “ <foo(); cout<<”main : val through derived “<
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.

derived:: foo() – ival : 1024 main : val through base : 1024 Derived :: foo() – ival : 2048 main : val through derived : 2048 ©Copyright 2004, Cognizant Academy, All Rights Reserved

170

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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

171

Pure Virtual Function class Base { public: virtual void show()=0 // Pure Virtual function }; class Derv1 : public Base { public: void show(){ cout<<”\n Derv 1”; } };

©Copyright 2004, Cognizant Academy, All Rights Reserved

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(); } 172

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; // illegal ptr=&b; // ok ptr->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.

©Copyright 2004, Cognizant Academy, All Rights Reserved

173

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. ©Copyright 2004, Cognizant Academy, All Rights Reserved

174

Virtual Function Implementation contd… Base vtbl;

Base b1;

Base::f1()

Base Members

Base::f2() Base::f3()

vptr

Derived d1; Base Members vptr

Derived vtbl; Base::f1() Derived::f2() Base::f3() Derived::f4()

Derived Members

©Copyright 2004, Cognizant Academy, All Rights Reserved

175

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

176

Object Oriented Programming: Next Step ll

Description

Reference Topic or Module

Book

OO A & D by Grady Booch

All

Book

Object oriented software concepts by Bertrand Mayer

All

PDF

http://www.kbcafe.com/articles/OOP.Concepts.pdf All

URL

http://www.desy.de/gna/html/cc/Tutorial/tutorial.html All http://www.bitpipe.com/rlist/term/Object-Oriented-Programming.html All http://www.well.com/user/ritchie/oo.html All http://www.planetpdf.com/codecuts/pdfs/ooc.pdf All

©Copyright 2004, Cognizant Academy, All Rights Reserved

177

Congratulations! You have successfully completed

Object Oriented Programming

Related Documents