function overloading
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 PresentationTRANSCRIPT
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); void print( double d, int length); void print( long l, int d); void print (long v, int length);
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.
Example
template <class Any> // template <typename Any>void swap ( Any &a, Any &b){ Any temp; temp=a; a=b; b=temp;}
#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;
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;}
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[ ]);
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};
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;}
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; }}
template <class Any> void show(Any a[]){ for(i=0;i<lim;i++) cout<<a[i]; cout<<endl;}
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
• In object-oriented programming the black boxes from which a program is manufactured are called objects
Levels of abstraction: A Real Life Example
• Black boxes in a car: transmission, electronic control module, etc.
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
• 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
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
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
Levels of abstraction: Software Design
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
• 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
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 };
Designing the Public Interface of a Class
Behavior of bank account (abstraction):
• deposit money • withdraw money • get balance
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();
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;}
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
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
Syntax : Method Definition
• returnType ClassName :: methodName(parameterType parameterName, . . .){method body
} Example: void BankAccount :: deposit(double amount)
{. . .}
Purpose: To define the behavior of a method
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 }
Encapsulation = Hiding data and providing access through methods
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?
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.
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;}
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
Class Destructor
class ClassName { …….. public : ~className(); ~className(int ); ……..};
Implementing Destructores
BankAccount :: ~BankAccount()
{ cout<<‘good bye”;
}
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
#include<iostream.h> // class definition ……….………..int main() { BankAccount harrysChecking = new BankAccount(); harrysChecking.deposit(2000); harrysChecking.withdraw(500); cout<<(harrysChecking.getBalance()); }
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.
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
CPP file #include<iostream.h>#include “bank1.h”BankAccount :: BankAccount()
{ balance = 0;}
BankAccount :: BankAccount(double initialBalance, string
str){ balance = initialBalance;
name=str;}
void BankAccount ::deposit(double amount{
balance =balance+amount ;}
void BankAccount::withdraw(double amount){ if ( amount > balance ) amount=0; else balance=balance-amount;}
double BankAccount :: getBalance(){ return balance;}BankAccount :: ~BankAccount(){
cout<<‘good bye”;}
#include<iostream.h>#include “bank1.h”int main() { BankAccount harrysChecking; harrysChecking.deposit(2000); harrysChecking.withdraw(500); cout<<(harrysChecking.getBalance()); return 0;}
Array of objects
BankAccount Bank[4]={ BankAccount(12.25, “Dave”), BankAccount(100.00, “Sue”), BankAccount(), BankAccount(200.00, “Ali”)};