Operator overloading in c++ is one of the effective feature that enables use to add to user defined data types with the same syntax as built-in data types. This means that C++ has the ability to provide the operators with a special meaning for a data type. The mechanism of giving such special meaning to an operator is known as operator overloading.
Operator overloading provides us to for the creation of new definitions for most of the C++ operators. But all operators present in the C++ are not overloaded. Here are some operators that can't be overloaded:
1. Class member access operators(. and .*)
2. Scope resolution operators(::)
3.SizeOf operator
4. Conditional operator
The remaining operators in C++ can be overloaded with same syntax. The common syntax is
return type classname :: operator(op-arglist)
{
function body
}
The process of overloading involves the following steps
Create a class that define the data type that is to be used in the overloading operation.
Declare the operator function operator op() in the public part of the class.
Define the operator function to implement the required operations.
C++ Rules to Operator Overloading
Source: https://docs.microsoft.com/en-us/cpp/cpp/general-rules-for-operator-overloading?view=vs-2019
- You cannot define new operators, such as dot operator
- You cannot redefine the meaning of operators when applied to built-in data types.
- Overloaded operators must either be a nonstatic class member function or a global function.
- Unary operators declared as member functions take no arguments; if declared as global functions, they take one argument.
- Binary operators declared as member functions take one argument; if declared as global functions, they take two arguments.
- If an operator can be used as either a unary or a binary operator (&, *, +, and -), you can overload each use separately.
- Overloaded operators cannot have default arguments.
- All overloaded operators except assignment (operator=) are inherited by derived classes.
- The first argument for member-function overloaded operators is always of the class type of the object for which the operator is invoked (the class in which the operator is declared, or a class derived from that class). No conversions are supplied for the first argument.
using namespace std; class complex { float x; float y; public: complex() { } complex(float real, folat imag) { x=real; y-imag' } void display(void); }; complex complex::operator+(complex c) // class name can be used as userdefined data type { complex temp; temp.x=x+c.x; temp.y=y+c.y; return(temp); } void complex::display(void) { cout<<x<"+"<y<"\n"; } int main() { complex c1.c2,c3; c1=complex(2.5,3.5); c2=complex(1.6,2.7); c3=c1+c2; cout<"c1=";c1.display(); cout<"c1=";c2.display(); cout<"c1=";c3.display(); return 0; }
0 comments :
Post a Comment
Note: only a member of this blog may post a comment.