Overloading Unary Operator Dr Piyush Kumar Singh Department

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

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

Overloading Unary Operator: •

Overloading Unary Operator: •

Example: Overloading Unary Minus Operator We are considering here unary minus operator to demonstrate

Example: Overloading Unary Minus Operator We are considering here unary minus operator 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, 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(); void operator-(); // 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) void space : : operator-()

Example: Overloading Unary Minus Operator (Program continued: Operator overloading) void space : : operator-() { x=-x; y=-y; z=-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”; -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