Sunday, May 18, 2008
What is Operator Overloading?
  • Mimics conventional usage of operators for user defined types.
  • Operator :: (scope resolution), . (member selection) and .* (member selection thru pointer to function) cannot be overloaded.

EXAMPLE: Demonstrate the usage of operator overloading


#include <iostream>
#include <ostream>

using namespace std;

class Employee {

    private:
        int iEmpId;
        string iEmpName;

    public:
        Employee(int, string);
         friend ostream& operator<<(ostream&, const Employee&);
};

// Constructor
Employee::Employee(int aEmpId, string aEmpName)
{
    iEmpId = aEmpId;
    iEmpName = aEmpName;
}

// Operator Overloading
ostream& operator<<(ostream& os, const Employee& emp)
{
    cout << "Emp Id = " << emp.iEmpId << endl;
    cout << "Emp Name = " << emp.iEmpName << endl;
    return os;
}

void main()
{
    Employee e1(100, "Employee1");
    Employee e2(200, "Employee2");
    cout << e1 << endl;
    cout << e2 << endl;
}
OUTPUT:
Emp Id = 100
Emp Name = Employee1

Emp Id = 200
Emp Name = Employee2

Contact Form

Name

Email *

Message *

Back to Top