Operator Overloading Lec-2
Operator Overloading Lec-2
class Date
{
public: // member functions
Date operator=(Date& d);
};
i = 1; i = 1;
j = ++i; j = i++;
(i is 2, j is 2) (i is 2, j is 1)
Solution
// prefix version
// postfix version
Postfix operator
Inventory& Inventory::operator++() // prefix version
{
Inventory *object = new Inventory(0,0);
numSold++;
object->numSold = numSold;
return(*object);
}
Employee emp2;
emp2.setValues(10,33.1);
if ( emp2 == emp1 )
cout <<“Both objects have equal value”;
else
cout <<“objects do not have equal value”;
}
Subscript operator [ ]
• With the help of [ ] operator, we can define array
style syntax for accessing or assigning individual
elements of classes
Student semesterGPA;
semesterGPA[0] = 3.5;
semesterGPA[1] = 3.3;
Subscript operator[ ]
class Student
{ private:
double gpa[8];
public:
Student ()
{ gpa[0]=3.5; gpa[1]=3.2; gpa[2]=4; gpa[3]=3.3;
gpa[4]=3.8; gpa[5]=3.6; gpa[6]=3.5; gpa[7]=3.8;
}
double& opeator[] (int Index);
}
}
Subscript operator[ ]
• How the statement executes?
semesterGPA[0]=3.7;
int main ( )
{
Student semesterGPA;
semesterGPA[0] = 3.7;
// the above statement is processed like as
semesterGPA.gpa[0] = 3.7
}
Calling an overloaded operator from native
data types
• In previous lectures, we were calling an overloaded
operator of a class only with the help of its object
(instance)
Point a, b, c;
// where + is overloaded in Point class
a = b + c;
Calling an overloaded operator from native
data types
• But, Can we call an overloaded operator of a class from
the variables of native data types?
int variable;
Point object;
variable = variable + object;