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

Презентация:



Advertisements
Похожие презентации
Unit II Constructor Cont… Destructor Default constructor.
Advertisements

Operator Overloading Customised behaviour of operators Chapter: 08 Lecture: 26 & 27 Date:
Loader Design Options Linkage Editors Dynamic Linking Bootstrap Loaders.
1/27 Chapter 9: Template Functions And Template Classes.
Inner Classes. 2 Simple Uses of Inner Classes Inner classes are classes defined within other classes The class that includes the inner class is called.
1/30 Chapter 8: Dynamic Binding And Abstract classes.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Route Selection Using Policy Controls Applying Route-Maps as BGP Filters.
2005 Pearson Education, Inc. All rights reserved. 1 Object-Oriented Programming: Interface.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Customer-to-Provider Connectivity with BGP Connecting a Multihomed Customer to Multiple Service.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Optimizing BGP Scalability Implementing BGP Peer Groups.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Route Selection Using Policy Controls Using Multihomed BGP Networks.
© 2009 Avaya Inc. All rights reserved.1 Chapter Two, Voic Pro Components Module Two – Actions, Variables & Conditions.
© Luxoft Training 2013 Annotations. © Luxoft Training 2013 Java reflection / RTTI // given the name of a class, get a "Class" object that // has all info.
2005 Pearson Education, Inc. All rights reserved. 1 Object-Oriented Programming: Polymorphism.
UNIT 2. Introduction to Computer Programming. COM E 211: Basic Computer Programming UNIT 2. Introduction to Computer Programming Algorithm & Flowcharting.
PAT312, Section 21, December 2006 S21-1 Copyright 2007 MSC.Software Corporation SECTION 21 GROUPS.
The waterfall model is a popular version of the systems development life cycle model for software engineering. Often considered the classic approach to.
© 2002 IBM Corporation Confidential | Date | Other Information, if necessary © Wind River Systems, released under EPL 1.0. All logos are TM of their respective.
A class is just a collection of variables--often of different types--combined with a set of related functions. The variables in the class are referred.
© 2006 Cisco Systems, Inc. All rights reserved. BSCI v Implementing BGP Explaining BGP Concepts and Terminology.
Транксрипт:

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

2 ©Copyright 2004, Cognizant Academy, All Rights Reserved Course Objective & Outline Course Objective: After completing this course, you will be able to understand the importance of OOPS in programming paradigm and basic terminologys involved into OOPS. Course Flow: 1 Programming paradigms 2 OOPS Concepts 3 Functions in C++ 5 Inheritance 6 Polymorphism 4 Classes and Objects

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

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

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

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

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

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

9 ©Copyright 2004, Cognizant Academy, All Rights Reserved Three types of control flow are used: - sequence - selection - iteration Structured Programming Y/N

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

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

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

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

14 ©Copyright 2004, Cognizant Academy, All Rights Reserved Object Oriented Programming Does not deal with programming in the sense of developing algorithms or data-structures Focuses on ADT

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

16 ©Copyright 2004, Cognizant Academy, All Rights Reserved Object Oriented Approach:

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

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

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

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

21 ©Copyright 2004, Cognizant Academy, All Rights Reserved Class & Object Account acct_no name balance withdraw() deposit( ) Account acct_no name balance withdraw() deposit( ) Patrick Patrick Meyer Meyer Account:acct1Account:acct2

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

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

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

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

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

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

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

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

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

31 ©Copyright 2004, Cognizant Academy, All Rights Reserved Inheritance Account acct_no name balance withdraw() deposit( ) Account acct_no name balance withdraw() deposit( ) Savings Acc interest Savings Acc interest Current Acc overdraft Current Acc overdraft

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

33 ©Copyright 2004, Cognizant Academy, All Rights Reserved C++: The History Bjarne Stroustrup developed C++ (originally named "C with Classes") during the 1980s. The name C++ was coined by Rick Mascitti in Standard was ratified in 1998 as ISO/IEC 14882:1998 New version of the standard (known informally as C++0x) is being developed.

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

35 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 data Destructors- freeing the memory Static functions- class oriented, modify only static data Non-static - object oriented Const functions- cannot modify data members values Virtual functions- help dynamic binding of function calls to implementation

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

37 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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; //30 cout<<hidden global a=<< ::a; //10; } cout<<hidden local a=<<a;//20; }

38 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 call displayHelloWorld( );// Global function call }

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

40 ©Copyright 2004, Cognizant Academy, All Rights Reserved Functions in C++ References Function Overloading Default values Inline Functions Function Templates Friend Functions Static Members and Functions Constant Functions and Constant data members

41 ©Copyright 2004, Cognizant Academy, All Rights Reserved Call by Value: void swap (int, int);//prototype main( ) { int x=4,y=5; cout<<x=<<x<< y=<<y;output: x=4 y=5 swap (x, y); //x, y actual args cout<<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

42 ©Copyright 2004, Cognizant Academy, All Rights Reserved Call by value: 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; } 4 x 5 y 5 a 4 b Parameter passing mechanisms

43 ©Copyright 2004, Cognizant Academy, All Rights Reserved Call by Address: void swap (int*, int*);//prototype main( ) { int x=4,y=5; cout<<x=<<x<< y=<<y;output: x=4 y=5 swap (&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

44 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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; } 4 x 5 y After calling change( ) X=5y=4 Parameter passing mechanisms

45 ©Copyright 2004, Cognizant Academy, All Rights Reserved Call by Reference: void swap (int&, int&);//prototype main( ) { int x=4,y=5; cout<<x=<<x<< y=<<y;output: x=4 y=5 swap (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

46 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 actualint cannot point to another variable int actualint = 123; int *const intptr = &actualint;

47 ©Copyright 2004, Cognizant Academy, All Rights Reserved Value of a reference cannot be changed int actualint = 123; int &otherint = actualint; 123 actualintotherint otherint otherint++ References & Constants int & const otherint = actualint; // Error Meaningless as all references are constants by definition

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

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

50 ©Copyright 2004, Cognizant Academy, All Rights Reserved Reference to a constant: Possible Constant reference declaration: Not Possible int actualint = 123; const int &otherint = actualint; readonly alias for actualint cant make any modification int & const otherint = actualint; // Error Meaningless as all references are constants by definition References and pointers

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

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

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

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

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

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

57 ©Copyright 2004, Cognizant Academy, All Rights Reserved Examples: // Declarations//Function calls int add(int a, int b);// prototype 1 int add(int a, int b, int c);// prototype 2 double add(double x, double y)// prototype 3 double add(int p, double q)// prototype 5 double 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

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

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

60 ©Copyright 2004, Cognizant Academy, All Rights Reserved Inline Functions inline ReturnType FunctionName(Parameters) { // Body of a main function } Keyword, function qualifier Syntax of inline function definition:

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

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

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

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

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

66 ©Copyright 2004, Cognizant Academy, All Rights Reserved Static Members contd., Static Data Members: Object A Object B Object C Static variable

67 ©Copyright 2004, Cognizant Academy, All Rights Reserved Static Member Example class account { private: int currentBal; static int RateofInt; }; myclass A(0), B(1); currentBal=0 Object A Object B Shared by all objects RateofInt Static Members contd., currentBal=1

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

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

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

71 ©Copyright 2004, Cognizant Academy, All Rights Reserved Illegal to declare a const member function that modifies a data member For built-in types it doesnt 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( ); --- } Constant data member and Constant Functions

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

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

74 ©Copyright 2004, Cognizant Academy, All Rights Reserved template ReturnType FunctionName(arguments of type identifier) Function Templates template // or template T square( T value1 ) { return value1 * value1; } template // or template 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

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

76 ©Copyright 2004, Cognizant Academy, All Rights Reserved Function Templates // definition of function template maximum template // or template 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, 3 1.1, 2.1, 1.8 A, B,C Input values C Output Maximum value

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

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

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

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

81 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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; } Inside sum( ) Inside main( ) x= 2 y= 4 Constructor declared Object created and initialized by constructor Constructor defined Object s x= 2 y= 4

82 ©Copyright 2004, Cognizant Academy, All Rights Reserved Constructors with arguments Parameters can be passed to the constructors 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

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

84 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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; } x= 1 y= 10 Object s1 Object s2 x= 8 y= 9 Default value for j=10 (Used by the object s1)

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

86 ©Copyright 2004, Cognizant Academy, All Rights Reserved Copy Constructors contd., 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; } Objects x=10 s1s2s3s4

87 ©Copyright 2004, Cognizant Academy, All Rights Reserved #include 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 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 = hello empty= s = hello empty= Copy Constructors contd.,

88 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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( ); } hello world hello world hello\0 data Copy Constructors contd., Shallow Copy

89 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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\0 data hello\0 Copy Constructors contd.,

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

91 ©Copyright 2004, Cognizant Academy, All Rights Reserved Destructors contd., Declaration –Same name as class Preceded with tilde (~) ~sum( ) { }

92 ©Copyright 2004, Cognizant Academy, All Rights Reserved Constant Objects const objects using const keyword before object declaration. For example: const sample s ( m, n); // object s is constant

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

94 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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) { clrscr(); account acc1; create_stobj(); getch(); } #include 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 constructor Account destructor Account constructor Account destructor Account constructor static account vip;

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

96 ©Copyright 2004, Cognizant Academy, All Rights Reserved #include 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 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= 2 a= 5 b=10 a = 4 b= 2 a= 5 b=10 Friend class example

97 ©Copyright 2004, Cognizant Academy, All Rights Reserved Template class #include Template 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); x.print( ); y.sum(2.2, 3.7); y.print( );} #include Template 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); x.print( ); y.sum(2.2, 3.7); y.print( );} The sum is : 5 The sum is : 5.9 The sum is : 5 The sum is : 5.9

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

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

100 ©Copyright 2004, Cognizant Academy, All Rights Reserved Inheritance Student Reg.No. Course Marks Teaching Staff Edn.Qual. Designation Specialization Person Name Sex Age Person is a generalization of Student. Student is a specialization of Person.

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

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

103 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 { ………… }; visibility mode

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

105 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 EmployeeStudent Part-time Student Class Employee {……..}; Class Student {……..}; Class Part-time Student : public Employee, public Student {…….};

106 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 StudentEmployee Class Person {……}; Class Student : public Person {……}; Class Employee : public Person {……};

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

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

109 ©Copyright 2004, Cognizant Academy, All Rights Reserved Person StudentEmployee Part-time Student Virtual Inheritance Class Person {……}; Class Student : public Person {……}; Class Employee : public Person {……}; Class Part-time Student : public Student, public Employee {…….};

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

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

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

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

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

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

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

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

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

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

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

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

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

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

124 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 invoked b1.putdata( ); // B::putdata( ) //is invoked b1.A::getdata( ); // A::getdata( ) // is invoked b1.A::putdata( ); // A::putdata( ) //is invoked }

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

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

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

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

129 ©Copyright 2004, Cognizant Academy, All Rights Reserved Types of polymorphism Polymorphism Operator Overloading Function Overloading Static Polymorphism Dynamic Polymorphism Virtual Fucntion

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

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

132 ©Copyright 2004, Cognizant Academy, All Rights Reserved To overload means give it an additional meaning. Function definition syntax for operator overloading Operator overloading

133 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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: integer addition floating point addition sita + "ram" - string concatenation In C++, this is called operator overloading

134 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 } KeywordOperator to be overloaded

135 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 } Operator to be overloaded

136 ©Copyright 2004, Cognizant Academy, All Rights Reserved Operators that can not be overloaded Operator Overloading ٫?: sizeof

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

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

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

140 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 The same operators can be defined in file scope (globally) using the following function heads: Unary Operators Overloading

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

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

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

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

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

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

147 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 > are overloaded for iostreams) you should use a non member function Non-member operators

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

149 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 required Conversion takes palce in Source class Conversion takes palce in Destination class Basic classNot applicableConstructor Class basicCasting OperatorNot Applicable Class classCasting operatorConstructor

150 ©Copyright 2004, Cognizant Academy, All Rights Reserved // spec1_conversion_functions2.cpp // C2666 expected #include 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.

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

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

153 ©Copyright 2004, Cognizant Academy, All Rights Reserved Polymorphism : Non–Virtual Functions class B{ public: void f(); }; class D: public B{ public: // f() not overridden }; void main(){ D d 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.

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

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

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

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

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

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

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

161 ©Copyright 2004, Cognizant Academy, All Rights Reserved Virtual Functions : Example 3 contd.. Output This is base fun() This is derive0 fun() This is derive1 fun()

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

163 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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(); } output Executing B::f() object d created successfully. Executing D::f()

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

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

166 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 Bs data members and methods, including constructors and destructors rather than to Ds methods. When f exits B::~B frees the 5 bytes. D::~D() fails to fire.

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

168 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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; } Output derived:: foo() – ival : 1024 main : val through base : 1024 Derived :: foo() – ival : 2048 main : 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.

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

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

171 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 dont convert derived class pointers to base class pointers with private/protected derivation. Always use public inheritance with polymorphism.

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

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

174 ©Copyright 2004, Cognizant Academy, All Rights Reserved 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 cant access any derived class members.