C++ language

Overloading in C++
Previous Home Next

overloading comes under compile time polymorphism. In Compile time polymorphism compiler is able to select the appropriate function for a particular call at the compile time itself.

In Compile time polymorphism there are two types of Overloading:

  1. Operator Overloading
  2. Function overloading
  1. Operator Overloading : Operator Overloading gives flexiable operation for the creation of new meeaning to operators used in C++ . In Operator Overloading , To operload an operator , a operator function is created which define the operation that the operator overload function will perform.
  2. // Example of operator overloading (- operator)
    
    #include <iostream>
    class example
    {
    int a,b,c;
    public:
    void inputdata(int x, int y, int z);
    void display();
    void operator -();
    };
    void counter :: inputdata(int x, int y, int z)
    {
    	a=x;
    	b=y;
    	c=z;
    }
    void counter :: display()
    {
    	cout<<"x="<<a<<endl;
    	cout<<"y="<<b<<endl;
    	cout<<"z="<<c<<endl;
    }
    void counter :: operator -()
    {
    	a=-a;
    	b=-b;
    	c=-c;
    }
    void main()
    {
    	counter obj1;
    	clrscr();
    	cout<<"abj1:"<<endl;
    	obj1.inputdata(30,20,-10);
    	obj1.display();
    	-obj1;
    	cout<<"obj1:"<<endl;
    	obj1.display();
    }
    
    Output
    obj1;
    x=30
    y=20
    z=-10
    obj1;
    x=-30
    y=-20
    z=10
    
  3. Function overloading Function overloading means two or more functions can have the same name but either the number of arguments or the data type of arguments has to be different. Return type has no role because function will return a value when it is called and at compile time compiler will not be able to determine which function to call.
  4. Example
    int add(int a, int b);
    int add(int a, int b , int c);
    int add(float a, float b);
    
    // function Overloading Example
    
    #include <iostream>
    #include<conio.h>
    #include <math.h>
    
    long add(long, long);
    float add(float, float);
     
    int main()
    {
       long a, b, x;
       float c, d, y;
     
       cout << "Enter two integers\n";
       cin >> a >> b;
        x = add(a, b);
        cout << "Sum of integers: " << x << endl;
        cout << "Enter two floating point numbers\n";
       cin >> c >> d;
        y = add(c, d);
        cout << "Sum of floats: " << y << endl;
        return 0;
    }
     long add(long x, long y)
    {
       long sum;
        sum = x + y;
        return sum;
    }
     float add(float x, float y)
    {
       float sum;
        sum = x + y;
        return sum;
    }
    
    Previous Home Next

    Tolal:0 Click:

    Show All Comments

    Did not find what you were looking for leave your name and message. We will revert within 24 hours
    Name:
    eMail:
    Comment / Feedback: