100 likes | 307 Views
Lab 2: Function Overloading. Presented By Nazia Hossain Lecturer, CSE Dept, Stamford University Bangladesh. Function Overloading. Overloading refers to the use of the same thing for different purposes.
E N D
Lab 2: Function Overloading Presented By NaziaHossain Lecturer, CSE Dept, Stamford University Bangladesh
Function Overloading • Overloading refers to the use of the same thing for different purposes. • We can use the same function name to create functions that perform a variety of different tasks. • Also known as polymorphism. • Would perform different operations depending on the argument list in the function call. • The correct function to be invoked is determined by • checking the number and type of the arguments but not on the function type.
//declarations • int add(int a, int b); • int add(int a, int b, int c); • int add(double x, double y); //function call • cout<< add(5, 10); • cout<< add(15, 10.0); • cout<< add(12.5, 7.5);
#include<iostream> using namespace std; int volume(int); double volume(double, int); int main(){ cout<<volume(10)<<"\n"; cout<<volume(2.5, 8)<<"\n"; return 0; } int volume(int s){ //cube return (s*s*s); } double volume(double r, int h){ //cylinder return (3.1416*r*r*h); }
Now write a program that would take different items as a item code and item price, also display them, if we need we could delete them and also show the total price
//array with class //processign shopping list #include<iostream> using namespace std; const int m=50; class ITEMS { intitemCode[m]; float itemPrice[m]; int count; public: void CNT(void){count=0;} void getitem(void); void displaySum(void); void remove(void); void displayItems(void); };
void ITEMS::getitem(void){ cout<<"Enter item code :"; cin>>itemCode[count]; cout<<"Enter item cost :"; cin>>itemPrice[count]; count++; } void ITEMS::displaySum(void){ float sum=0; for(int i=0; i<count; i++){ sum=sum+itemPrice[i]; } cout<<"\nTotal value :"<<sum<<"\n"; }
void ITEMS::remove(void){ int a; cout<<"Enter item code"; cin>>a; for(int i=0;i<count;i++){ if(itemCode[i] == a) itemPrice[i]=0; } } void ITEMS::displayItems(void){ cout<<"\nCode Price\n"; for(int i=0; i<count; i++){ cout<<"\n"<<itemCode[i]; cout<<" "<<itemPrice[i]; } cout<<"\n"; }
int main(){ ITEMS order; order.CNT(); int x; do { cout<<"\nYou can do the following;" <<"Enter the appropriate number\n"; cout<<"\n1: Add an item"; cout<<"\n2: Display the total value"; cout<<"\n3: Delete an item"; cout<<"\n4: Display all items"; cout<<"\n5: Quit"; cout<<"\n\nWhat is your option?"; cin>>x;
switch(x){ case 1: order.getitem(); break; case 2: order.displaySum(); break; case 3: order.remove(); break; case 4: order.displayItems(); break; case 5: break; default: cout<<"Error in input; try again\n"; } } while(x!=5); return 0; }