Chapter-7 OOPC Old
Chapter-7 OOPC Old
Operator Overloading
Weightage: 11%
Hours: 6 Hours needed
Polymorphism
C++ permits us to add two variables of user defined types with the same syntax that is applied to the
basic data types.
• Create a class that defines 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.
3/14/2021 | U & P U. Patel Department of Computer Engineering
Overloading Unary Operators
• Consider unary minus operator (changes the sign of the operand)
• The unary minus when applied to an object should change the sign of each of its data items.
• For e.g: A binary operator + can be overloaded to add two objects rather than adding two
variables.
• Using operator overloading a functional notation,
• C = sum(A, B);
• Can be replaced by,
• C = A + B;
• The compiler invokes an appropriate constructor, initializes an object with no name and returns the
contents for copying into an object.
• Such an object is called a temporary object and goes out of space as soon as the contents are assigned to
another object.
• A friend function requires two arguments to be explicitly passed to it, while a member
function requires only one.
• For e.g:
C3 = C1 + C2;
Is equivalent to
C3 = operator+(C1, C2);
• C++ permits us to create our own definitions of operators that can be used to
manipulate the strings very much similar to other built-in data types.
• ANSI C++ committee has added a new class called string to the C++ class library that
supports all kinds of string manipulations.
• Since the strings vary in size, we use new to allocate memory for each string and a
pointer variable to point to the string array.
• int m;
• float x = 3.14159;
• // to m.
• For user defined data types, the compiler does not support automatic type conversions.
• The class Y type data is converted to the class X type data and the converted value is
assigned to the objX.