1 / 46

Function Overloading

Function Overloading. Having more than one function with the same name. list of argument of a function are called signature of a function. We can have more than one function with the same name but they must have different signatures. void print ( char * str, int length);

Download Presentation

Function Overloading

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Function Overloading Having more than one function with the same name. list of argument of a function are called signature of a function. We can have more than one function with the same name but they must have different signatures.

  2. void print ( char * str, int length); void print( double d, int length); void print( long l, int d); void print (long v, int length);

  3. Function Template A function template is a generic function description. We define a function as a generic type and we use it as a specific type ( double or int,…) later on.

  4. Example template <class Any> // template <typename Any> void swap ( Any &a, Any &b) { Any temp; temp=a; a=b; b=temp; }

  5. #include<iostream.h> template<class Any> //template <typename Any> void swap ( Any &a, Any &b); int main() { int i=10; int j=20; cout<<“i, j=“<<i<<“ “<<“, “<<j<<“. \n”; swap(i,j); cout<<“Now i, j=“<<i<<“ “<<“, “<<j<<“. \n”; double x=24.5; double y=81.7;

  6. cout<<“x, y=“<<x<<“ “<<“, “<<y<<“. \n”; swap(x,y); cout<<“Now x, y=“<<x<<“ “<<“, “<<y<<“. \n”; return 0; } template <class Any> void swap ( Any &a, Any &b) { Any temp; temp=a; a=b; b=temp; }

  7. Overloaded Template #include<iostream.h> template<class Any> //template <typename Any> void swap ( Any &a, Any &b); // original template template<class Any> void swap(Any *a, Any *b, int n); template<class Any> void show(Any a[ ]);

  8. const int lim=8; int main() { int i=10; int j=20; cout<<“i, j=“<<i<<“ “<<“, “<<j<<“. \n”; swap(i,j); cout<<“Now i, j=“<<i<<“ “<<“, “<<j<<“. \n”; int d1[lim]={0,7,0,4,1,7,7,6}; int d2[lim]={0,6,2,0,1,9,6,9};

  9. show(d1); show(d2); swap(d1,d2,lim); return 0; } template <class Any> void swap ( Any &a, Any &b) { Any temp; temp=a; a=b; b=temp; }

  10. template <class Any> void swap ( Any []a, Any []b, int n) { Any temp; for( int i=0; i< n; i++) { temp=a[i]; a[i]=b[i]; b[i]=temp; } }

  11. template <class Any> void show(Any a[]) { for(i=0;i<lim;i++) cout<<a[i]; cout<<endl; }

  12. Introduction to OOP Black Box : • A black box magically does its thing • Hides its inner workings • Encapsulation: the hiding of unimportant details • Abstraction: taking away inessential features, until only the essence of the concept remains

  13. In object-oriented programming the black boxes from which a program is manufactured are called objects

  14. Levels of abstraction: A Real Life Example • Black boxes in a car: transmission, electronic control module, etc.

  15. Levels of abstraction: A Real Life Example • Users of a car do not need to understand how black boxes work • Interaction of a black box with outside world is well-defined • Drivers interact with car using pedals, buttons, etc. • Mechanic can test that engine control module sends the right firing signals to the spark plugs • For engine control module manufacturers, transistors and capacitors are black boxes magically produced by an electronics component manufacturer

  16. Encapsulation leads to efficiency: • Mechanic deals only with car components (e.g. electronic control module), not with sensors and transistors • Driver worries only about interaction with car (e.g. putting gas in the tank), not about motor or electronic control module

  17. Objects and Classes • Object: entity that you can manipulate in your programs (by calling methods) • Each object belongs to a class. For example, cout belongs to the class iostream

  18. Method (Function) Method : Sequence of instructions that accesses the data of an object You manipulate objects by calling its methods Class: Set of objects with the same behavior

  19. Levels of abstraction: Software Design

  20. Levels of abstraction: Software Design • Old times: computer programs manipulated primitive types such as numbers and characters • Manipulating too many of these primitive quantities is too much for programmers and leads to errors • Solution: Encapsulate routine computations to software black boxes • Abstraction used to invent higher-level data types

  21. In object-oriented programming, objects are black boxes • Encapsulation: Programmer using an object knows about its behavior, but not about its internal structure • In software design, you can design good and bad abstractions with equal facility; understanding what makes good design is an important part of the education of a software engineer • First, define behavior of a class; then, implement it

  22. Designing the Public Interface of a Class class ClassName { private : instance fields; // we can have methods as well public : constructors; // header definition methods; // header definition destructors; // header definition };

  23. Designing the Public Interface of a Class Behavior of bank account (abstraction): • deposit money • withdraw money • get balance

  24. Designing the Public Interface of a Class: Methods • Methods of BankAccount class: • deposit • withdraw • getBalance • We want to support method calls such as the following:harrysChecking.deposit(2000);harrysChecking.withdraw(500);cout<<harrysChecking.getBalance();

  25. Instance Fields An object stores its data in instance fields Field: a technical term for a storage location inside a block of memory Instance of a class: an object of the class The class declaration specifies the instance fields: class BankAccount{     private :   double balance; string name;}

  26. Instance Fields • An instance field declaration consists of the following parts: • specifying access (such as private) • type of variable (such as double) • name of variable (such as balance) • Each object of a class has its own set of instance fields • You should declare all instance fields as private

  27.  Syntax : Instance Field Declaration class ClassName { accessSpecifier: fieldType fieldName;. . . }; Example:   class BankAccount{private: double balance;. . .} Purpose: To define a field that is present in every object of a class

  28. Syntax : Method Definition • returnType ClassName :: methodName(parameterType parameterName, . . .){method body } Example: void BankAccount :: deposit(double amount){. . .} Purpose: To define the behavior of a method

  29. Accessing Instance Fields The deposit method of the BankAccount class can access the private instance field: void BankAccount :: deposit(double amount){   double newBalance = balance + amount;balance = newBalance;} Other methods cannot:   int main()   {     BankAccount momsSavings = new BankAccount(1000);     . . .     momsSavings.balance = -1000; // ERROR   }

  30. Encapsulation = Hiding data and providing access through methods

  31. Self Check • How can you use the methods of the public interface to empty the harrysChecking bank account? • Suppose you want a more powerful bank account abstraction that keeps track of an account number in addition to the balance. How would you change the public interface to accommodate this enhancement?

  32. Answer • harrysChecking.withdraw(harrysChecking.getBalance()) • Add an accountNumber parameter to the constructors, and add a getAccountNumber method. There is no need for a setAccountNumber method–the account number never changes after construction.

  33. Implementing Constructors • Constructors contain instructions to initialize the instance fields of an object BankAccount :: BankAccount(){ balance = 0;}BankAccount :: BankAccount(double initialBalance, string str){ balance = initialBalance; name=str;}

  34. Constructor Call Example BankAccount harrysChecking = new BankAccount(1000,”Dave”); • Create a new object of type BankAccount • Call the second constructor (since a construction parameter is supplied) • Set the parameter variable initialBalance to 1000 • Set the balance instance field of the newly created object to initialBalance • Return an object reference, that is, the memory location of the object, as the value of the new expression • Store that object reference in the harrysChecking variable

  35. Class Destructor class ClassName { …….. public : ~className(); ~className(int ); …….. };

  36. Implementing Destructores BankAccount :: ~BankAccount(){ cout<<‘good bye”; }

  37. Testing a Class • Test class: a class with a main method that contains statements to test another class. • Typically carries out the following steps: • Construct one or more objects of the class that is being tested • Invoke one or more methods • Print out one or more results

  38. #include<iostream.h> // class definition ………. ……….. int main() { BankAccount harrysChecking = new BankAccount(); harrysChecking.deposit(2000); harrysChecking.withdraw(500); cout<<(harrysChecking.getBalance()); }

  39. Each class in separate file We use a header file “Name.h” to use a class later or separate the classes. Each header file ( .h) declare a class. We use a .cpp file to implement the body of the methods.

  40. Header file for BankAccount class /////////// bank1.h #ifndef BANK1_H #define BANK1_H class BankAccount { private : double balance; string name; public : BankAccount(); BankAccount(double initial_balance); void deposit (double amount); void withdraw (double amount ); double getBalance(); ~BankAccount(); }; #endif

  41. CPP file #include<iostream.h> #include “bank1.h” BankAccount :: BankAccount(){ balance = 0;} BankAccount :: BankAccount(double initialBalance, string str){ balance = initialBalance; name=str;}

  42. void BankAccount ::deposit(double amount {balance =balance+amount ; } void BankAccount::withdraw(double amount) { if ( amount > balance ) amount=0; else balance=balance-amount; }

  43. double BankAccount :: getBalance() { return balance; } BankAccount :: ~BankAccount() { cout<<‘good bye”; }

  44. #include<iostream.h> #include “bank1.h” int main() { BankAccount harrysChecking; harrysChecking.deposit(2000); harrysChecking.withdraw(500); cout<<(harrysChecking.getBalance()); return 0; }

  45. Array of objects BankAccount Bank[4]={ BankAccount(12.25, “Dave”), BankAccount(100.00, “Sue”), BankAccount(), BankAccount(200.00, “Ali”) };

More Related