Binary '+' Operator Overloading


#include <iostream.h>
/*----------------------Class definition-------------------------*/
class sample
{
        int a;
        int b;
    public :
        sample() { }        // default empty constructor
        sample(int, int);

        // Overloaded binary addition operator
        sample operator + (sample);
        void print();
};
sample::sample(int x, int y)
{
    a = x;
    b = y;
}

// Overloaded binary addition operator as a member function
// Returns an object as a value of the addition
sample sample::operator + (sample x)
{
    sample temp;
    temp.a = a + x.a;
    temp.b = b + x.b;
    return temp;
}
void sample::print()
{
    cout << "a = " << a << "\n";
    cout << "b = " << b << "\n";
}
/*----------------------Definition ends here---------------------*/
void main(void)
{
    sample A(5,10), B(5,5), C;
    cout << "The result of the addition is :\n";
    C = A + B;    // invocation of the operator function
    C.print();
    cout << "\nSecond method of invocation of operator function- \n";
    cout << "The result of the addition is :\n";
    C = A.operator + (B);    // different way of invocation
    C.print();
}

0 comments:

Post a Comment

 
 
 
 


Copyright © 2012 http://codeprecisely.blogspot.com. All rights reserved |Term of Use and Policies|