Overloading Unary Operator Using friend Function Dr Piyush

  • Slides: 10
Download presentation
Overloading Unary Operator Using friend Function Dr. Piyush Kumar Singh Department of Computer Science

Overloading Unary Operator Using friend Function Dr. Piyush Kumar Singh Department of Computer Science

Overloading Unary Operator: Unary Overloaded Operator using friend functions can be invoked by the

Overloading Unary Operator: Unary Overloaded Operator using friend functions can be invoked by the expressions as given below operator op (x) Where op is operator function, x is the operand Operator is keyword.

Example: Overloading Unary Minus Operator We are defining here unary minus operator using friend

Example: Overloading Unary Minus Operator We are defining here unary minus operator using friend function to demonstrate the unary operator overloading in C++. A minus operator when used as unary, takes just one operand. As it is known that this operator changes the sign of an operand when applied to a basic data item. The program given below demonstrate that how to overload this operator using friend function, so that it can be applied to an object in much the same way as it can be on int and float variables.

Example: Overloading Unary Minus Operator (Program: Class definition) #include<iostream. h> class space { int

Example: Overloading Unary Minus Operator (Program: Class definition) #include<iostream. h> class space { int x; int y; int z; public: void getdata(int a, int b, int c); void display(); friend void operator-(space &s); }; // overload unary operator

Example: Overloading Unary Minus Operator (Program continued: Member function definition) void space: : getdata(int

Example: Overloading Unary Minus Operator (Program continued: Member function definition) void space: : getdata(int a, int b, int c) { x=a; y=b; z=c; } void space: : display() { cout << x << “ “; cout << y << “ “; cout << z << “ “; }

Example: Overloading Unary Minus Operator (Program continued: Operator overloading using friend) void operator-(space &S

Example: Overloading Unary Minus Operator (Program continued: Operator overloading using friend) void operator-(space &S 1) { S 1. x=-S 1. x; S 1. y=-S 1. y; S 1. z=-S 1. z; }

Example: Overloading Unary Minus Operator (Program continued, main function) int main () { space

Example: Overloading Unary Minus Operator (Program continued, main function) int main () { space S; S. getdata(10, -20, 30); cout<< “S: ”; S. display(); cout<<“n”; operator-(S); // activates operator-() function cout<<“S : ”; S. display(); return 0; }

Output: S: 10 -20 30 S: -10 20 -30

Output: S: 10 -20 30 S: -10 20 -30

References: 1. Object Oriented Programming with C++, 3/e by E. Balagurusamy, Tata Mc. Graw

References: 1. Object Oriented Programming with C++, 3/e by E. Balagurusamy, Tata Mc. Graw Hill. 2. Mastering C++, 1/e by Venugopal, Tata Mc. Graw Hill.

Thank You

Thank You