Object Oriented Programming in C MAITRAYEE MUKERJI Polymorphism
Object Oriented Programming in C++ MAITRAYEE MUKERJI
Polymorphism �Poly: Multiple, Many �Morphism: Forms, Behavior �Polymorphism One thing with several distinct forms or behavior In C++ refers to way in which operators or functions can behave depending on what they are operating on: - standard data types, user defined data types, same function but with different signatures (number and type of arguments), objects belonging to base or derived classes
Polymorphism �Compile Time Polymorphism Operator Overloading Function Overloading �Run Time Polymorphism Function Overriding �Templates
Operator Overloading �Operator overloading refers to giving the normal C++ operators (+, *, <=, ++ etc. ) additional meaning when they are applied to user defined data types. �Example: My. Object d 1, d 2, d 3; d 3 = d 1 + d 2; �Extending C++ Using classes to create new kinds of variable Using operator overloading to create new definitions for operators
Overloading Unary Operator �Counter is a variable that counts things Nodes, persons, file access etc. �Each time an event takes place, the counter is incremented by 1 �The Counter can be accessed to find the current count
// object represents a counter variable Class Counter { Since count is always positive private: unsigned int count; Constructor and public: Initialization to zero Counter () : count (0); {} int get_count() { return count; } void inc_count() { count++; } }
Main () { Counter C 1; cout << “n C 1=“ << C 1. get. Count(); ++C 1; C 1. inc_count (); cout << “n C 1=“ << C 1. get. Count(); cout << endl; return 0; }
// object represents a counter variable Class Counter { private: unsigned int count; public: Counter () : count (0); {} int get_count() { return count; } void inc_count() void operator ++ () {count++; } {++ count; } } The keyword operator is used for overloading the ++ operator
Overloading Binary Operators �Adding and Subtracting Two Complex Numbers C 1 = 4 + 3 i C 2 = 3 + 6 i CAdd = C 1+C 2 CSub = C 1 -C 2
struct Complex { float }; real; imag; int main() { Complex C 1, C 2, C 3; Complex operator+ (const Complex &C 1, const Complex &C 2) { Complex C 3; C 3. real = C 1. real + C 2. real; C 3. imag = C 1. imag + C 2. imag; return C 3; } C 1. real = 4; C 1. imag = 2; C 2. real = 5; C 2. imag = 4; C 3. real = C 1. real + C 2. real; C 3 = C 1 + C 2 C 3. imag = C 1. imag + C 2. imag; cout << C 3. real << " " << C 3. imag ; C 3. real = C 1. real - C 2. real; C 3 = C 1=- C 2 C 3. imag C 1. imag - C 2. imag; cout << C 3. real << " " << C 3. imag ; return 0; } Complex operator- (const Complex &C 1, const Complex &C 2) { Complex C 3; C 3. real = C 1. real - C 2. real; C 3. imag = C 1. imag - C 2. imag; return C 3; }
Function Overloading �An overloaded function can perform different activities depending on the number and type of data sent to it. �More than one function with the same name but Different type of input argument Different number of input arguments Different number and type of input arguments
// Example: Different Type of Input Arguments #include <iostream> using namespace std; void print. Number (int x) { cout << “I am printing an Integer” << x << endl; } void print. Number (float x) { cout << “I am printing a Float” << x << endl; } int main() { int a= 54; float b = 34. 5678; print. Number (a); print. Number (b); }
// Different number of input arguments // Printing a line of characters void print. Char(); void print. Char(char); void print. Char (char, int); //prints “*” , 45 times in a row // prints the specified character, #times specified by user int main( ) { print. Char (); print. Char (‘=‘); print. Char (‘+’, 15); return 0; } void print. Char( ) { for (int j = 0; j<45; j++) cout << “*”; cout << endl; }
void print. Char( char ch) { for (int j = 0; j<45; j++) cout << ch; cout << endl; } void print. Char( char ch, int n) { for (int j = 0; j<n; j++) cout << ch; cout << endl; }
Inheritance & Polymorphism �“many form” : ability of a variable to take different types �In C++, applied mainly on pointer variables S: Base Class T: Derived Class p: Pointer to class S -> p can point to any object belonging to any derived class T of S a( ): Virtual function in both S and T Function Call: p->a() invokes � S: : a() � T: : a () if p points to object of class S if dynamic binding is used and p points to object type T – T is said to overide function a() from S
Example class Base. A { public: int a; void print. Data () { cout << "Printing Data In Base Class: " << a << endl; } void print. Msg () { cout << "Printing Msg in Base Class: " << "Hello World" << endl; } }; class Derived. A : public Base. A { public: void print. Data (){ cout << "Printing Data In Derived Class: " << a << endl; } };
Example …contd Code Fragment 1 Code Fragment 2 Code Fragment 3 Base. A* p. Base; p. Base = new (Base. A); Base. A* p. Base; p. Base = new (Derived. A); Derived. A* p. Derived p. Base->a = 100; p. Base->a = 200; p. Derived->a = 300; p. Base->print. Data(); p. Base->print. Msg(); p. Derived->print. Data(); p. Derived->print. Msg(); p. Derived = new (Derived. A); Printing Data In Base Class: 100 Printing Data In Base Class: 200 Printing Data In Derived Class: 300 Printing Msg in Base Class: Hello World
Example class Base. A { public: int a; virtual void print. Data () { cout << "Printing Data In Base Class: " << a << endl; } void print. Msg () { cout << "Printing Msg in Base Class: " << "Hello World" << endl; } }; class Derived. A : public Base. A { public: virtual void print. Data (){ cout << "Printing Data In Derived Class: " << a << endl; } };
Example …contd Code Fragment 1 Code Fragment 2 Code Fragment 3 Base. A* p. Base; p. Base = new (Base. A); Base. A* p. Base; p. Base = new (Derived. A); Derived. A* p. Derived p. Base->a = 100; p. Base->a = 200; p. Derived->a = 300; p. Base->print. Data(); p. Base->print. Msg(); p. Derived->print. Data(); p. Derived->print. Msg(); p. Derived = new (Derived. A); Printing Data In Base Class: 100 Printing Data In Derived Class: 200 Printing Data In Derived Class: 300 Printing Msg in Base Class: Hello World
Object Oriented Programming in C++: Templates MAITRAYEE MUKERJI
Templates �Templates make it possible to use one function or class to handle many different data types �Another way of implementing polymorphism Function Template Class Templates Standard Template Libraries
Function Overloading - Recap �Function that returns absolute values of two numbers. int abs (int n) {return (n<0) ? -n: n; } float abs (float n) {return (n<0) ? -n: n; } double abs (double n) {return (n<0) ? -n: n; } �Repetitive, time-consuming, long code �Error, if found, needs to be corrected in all codes
Function Template �Function Template: an automatic mechanism provided by C++, to produce a generic function for an arbitrary type T. �A function template provides a well-defined pattern from which a concrete function may later be formally defined or instantiated.
Function Template - Example template < class any. Type> any. Type abs (any. Type n) {return (n<0) ? –n: n; } int any. Type abs (any. Type n) {return (n<0) ? –n: n; } float any. Type abs (any. Type n) {return (n<0) ? –n: n; } template parameter declaration
Instantiation �C++ does not compile the template function directly. Instead, at compile time, when the compiler encounters a call to a template function, it replicates the template function and replaces the template type parameters with actual types! The function with actual types is called a function template instance.
Function Templates – example �Function to find the minimum of two numbers int. Min(int a, int b) { return (a < b ? a : b); } // returns the minimum of a and b template <class T> T gen. Min(T a, T b) { // returns the minimum of a and b return (a < b ? a : b); }
Example. . contd main () { int a = gen. Min (2, 10); cout << a << endl; double b = gen. Min (4. 6, 6. 4); cout << b << endl; return 0; }
Function Template �Template functions for swapping two values �Template function for searching an array for a specific value. The function returns the array index for the value if it finds it, otherwise -1
Function Template // Swapping two numbers template <typename T> void myswap (T& tmp 1, T& tmp 2) { T temp; temp = tmp 1; tmp 1 = tmp 2; tmp 2 = temp; return 0; }
Function Template – Array Search // searching for a value in an array Template <class atype> int find(atype* array, atype value, int size) { for (int j=0; j<size; j++) if (array[j] == value) return j; return -1; }
Class Template �In C++ we can have class templates also �It allows us to provide one data structure declaration / data storage that can be applied to many different types. �Standard Template Library uses class templates extensively.
Class Template Example template <class T> class Stack { private: T st[MAX]; int top; public: Stack() { top = -1; } T var); void push (int {st[++top] = var; } int T pop(); {return st[top--]; } }
Class Template Example template <class T> Stack<Type>: : Stack() {top = -1} template <class T> Stack<Type>: : Push(Type var) { st[++top] = var; } template <class T> Type Stack<Type>: : Pop() { return st[top --]; }
Instantiation �Classes are instantiated by defining an object using the template argument Stack <float> s 1; Stack <long> s 2;
Example Class Node { public: Node(string s); private: string data; Node* previous; Node* next; };
Contd. template <typename T> Class Node { public: Node(T s); private: T data; Node<T>* previous; Node<T>* next; };
Reference �Lafore �Horstmann
- Slides: 37