Polymorphism in c++

Polymorphism in c++


Function overloading in c++:


  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. class Shape{  
  5. public:  
  6.     void add(int a,int b){  
  7.         cout<<"Sum: "<<a+b<<endl;  
  8.     }  
  9.     void add(double a,double b){  
  10.         cout<<"Sum: "<<a+b<<endl;  
  11.     }  
  12.     void add(string a,string b){  
  13.         cout<<"Sum: "<<a+b<<endl;  
  14.     }  
  15. };  
  16.   
  17. int main()  
  18. {  
  19.     int a=5,b=10;  
  20.     double x=3.5,y=6.7;  
  21.     string s1="hello",s2=" world!";  
  22.   
  23.     Shape obj;  
  24.     obj.add(a,b);  
  25.     obj.add(x,y);  
  26.     obj.add(s1,s2);  
  27.     return 0;  
  28. }  


Operator Overloading in C++:


  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. class Volume{  
  5. private:  
  6.     int length;  
  7.     int width;  
  8.     int height;  
  9. public:  
  10.     Volume(){  
  11.         length=0;  
  12.         width=0;  
  13.         height=0;  
  14.     }  
  15.     Volume(int a,int b,int c){  
  16.         length=a;  
  17.         width=b;  
  18.         height=c;  
  19.     }  
  20.     Volume operator +(Volume vol2){/// Operator overloading  
  21.         Volume temp;  
  22.         temp.length=length+vol2.length;  
  23.         temp.width=width+vol2.width;  
  24.         temp.height=height+vol2.height;  
  25.         return temp;  
  26.     }  
  27.     Volume operator +(int x){/// Operator overloading  
  28.         Volume temp;  
  29.         temp.length=length+x;  
  30.         temp.width=width+x;  
  31.         temp.height=height+x;  
  32.         return temp;  
  33.     }  
  34.     void getVolume(){  
  35.         cout<<"Length: "<<length<<endl;  
  36.         cout<<"Width: "<<width<<endl;  
  37.         cout<<"Height: "<<height<<endl;  
  38.     }  
  39. };  
  40.   
  41.   
  42. int main()  
  43. {  
  44.     int n=5;  
  45.     Volume vol1(2,3,4);  
  46.     Volume vol2(1,2,3);  
  47.     Volume vol3;  
  48.     vol3=vol1+vol2;///Add two object  
  49.     //vol3=vol1+n;///Add variable with object  
  50.     vol3.getVolume();  
  51.     return 0;  
  52. }  

Share:

0 Comments:

Post a Comment