function overloading

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

Upload: iona-herrera

Post on 15-Mar-2016

70 views

Category:

Documents


1 download

DESCRIPTION

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); - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: 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.

Page 2: Function Overloading

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

Page 3: Function Overloading

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.

Page 4: Function Overloading

Example

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

Page 5: Function Overloading

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

Page 6: Function Overloading

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

Page 7: Function Overloading

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

Page 8: Function Overloading

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

Page 9: Function Overloading

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

Page 10: Function Overloading

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

Page 11: Function Overloading

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

Page 12: Function Overloading

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

Page 13: Function Overloading

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

Page 14: Function Overloading

Levels of abstraction: A Real Life Example

• Black boxes in a car: transmission, electronic control module, etc.

Page 15: Function Overloading
Page 16: Function Overloading

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

Page 17: Function Overloading

• 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

Page 18: Function Overloading

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

Page 19: Function Overloading

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

Page 20: Function Overloading

Levels of abstraction: Software Design

Page 21: Function Overloading

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

Page 22: Function Overloading

• 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

Page 23: Function Overloading

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

Page 24: Function Overloading

Designing the Public Interface of a Class

Behavior of bank account (abstraction):

• deposit money • withdraw money • get balance

Page 25: Function Overloading

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

Page 26: Function Overloading

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

Page 27: Function Overloading

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

Page 28: Function Overloading

 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

Page 29: Function Overloading

Syntax : Method Definition

• returnType ClassName :: methodName(parameterType parameterName, . . .){method body

} Example: void BankAccount :: deposit(double amount)

{. . .}

Purpose: To define the behavior of a method

Page 30: Function Overloading

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   }

Page 31: Function Overloading

Encapsulation = Hiding data and providing access through methods

Page 32: Function Overloading

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?

Page 33: Function Overloading

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.

Page 34: Function Overloading

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

Page 35: Function Overloading

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

Page 36: Function Overloading

Class Destructor

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

Page 37: Function Overloading

Implementing Destructores

BankAccount :: ~BankAccount()

{ cout<<‘good bye”;

}

Page 38: Function Overloading

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

Page 39: Function Overloading

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

Page 40: Function Overloading

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.

Page 41: Function Overloading

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

Page 42: Function Overloading

CPP file #include<iostream.h>#include “bank1.h”BankAccount :: BankAccount()

{ balance = 0;}

BankAccount :: BankAccount(double initialBalance, string

str){ balance = initialBalance;

name=str;}

Page 43: Function Overloading

void BankAccount ::deposit(double amount{

    balance =balance+amount ;}

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

Page 44: Function Overloading

double BankAccount :: getBalance(){ return balance;}BankAccount :: ~BankAccount(){

cout<<‘good bye”;}

Page 45: Function Overloading

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

Page 46: Function Overloading

Array of objects

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