Polymorphism in c++
Function overloading in c++:
- #include<iostream>
- using namespace std;
-
- class Shape{
- public:
- void add(int a,int b){
- cout<<"Sum: "<<a+b<<endl;
- }
- void add(double a,double b){
- cout<<"Sum: "<<a+b<<endl;
- }
- void add(string a,string b){
- cout<<"Sum: "<<a+b<<endl;
- }
- };
-
- int main()
- {
- int a=5,b=10;
- double x=3.5,y=6.7;
- string s1="hello",s2=" world!";
-
- Shape obj;
- obj.add(a,b);
- obj.add(x,y);
- obj.add(s1,s2);
- return 0;
- }
Operator Overloading in C++:
- #include<iostream>
- using namespace std;
-
- class Volume{
- private:
- int length;
- int width;
- int height;
- public:
- Volume(){
- length=0;
- width=0;
- height=0;
- }
- Volume(int a,int b,int c){
- length=a;
- width=b;
- height=c;
- }
- Volume operator +(Volume vol2){
- Volume temp;
- temp.length=length+vol2.length;
- temp.width=width+vol2.width;
- temp.height=height+vol2.height;
- return temp;
- }
- Volume operator +(int x){
- Volume temp;
- temp.length=length+x;
- temp.width=width+x;
- temp.height=height+x;
- return temp;
- }
- void getVolume(){
- cout<<"Length: "<<length<<endl;
- cout<<"Width: "<<width<<endl;
- cout<<"Height: "<<height<<endl;
- }
- };
-
-
- int main()
- {
- int n=5;
- Volume vol1(2,3,4);
- Volume vol2(1,2,3);
- Volume vol3;
- vol3=vol1+vol2;
-
- vol3.getVolume();
- return 0;
- }
0 Comments:
Post a Comment