Chapter 4
Chapter 4
Overloading
Objective
#include <iostream.h>
class FriendDemo {
int a, b;
public:
friend int sum(FriendDemo fd);
void setvalue(int i, int j);
};
void FriendDemo::setvalue(int i, int j)
{
a = i;
b = j;
}
int sum(FriendDemo x)
{
return x.a + x.b;
}
int main()
{
FriendDemo fd_ob;
fd_ob.setvalue(30, 40);
cout << sum(fd_ob);
return 0;
}
Operator Overloading
Operator overloading
Operator overloading means giving capability to the operator to work on
different types of operands.
The operators +,* etc, works for type int, float etc. we can overload these
operators by giving them the capability to work on derived data types.
By making the operators to work on derived data types just like they work
on built-in data types, we can have a consistent approach.
This is done with the help of special function called operator function.
Syntax for operator overloading
return-type classname::operator #(arg-list)
{
//operations
}
Often, operator functions returns an object of the class they operate on,but
ret-type can be any valid type. The # is a placeholder. When you create an
operator function, substitute the operator for the #.
Operator functions must be either member functions (nonstatic ) or friend
function.
A member function has no arguments for unary operators and only one for
binary operators.
And if there is a friend function then a friend function will have only one
argument for unary operators and two for binary operators.
Arguments may be passed either by value or by reference.
Rules for overloading operators
}
Namespaces in C++
Namespaces in C++
The namespace keyword allows you to partition the global namespace by creating a
declarative region.
A namespace defines a scope.
Anything defined within a namespace statement is within the scope of that
namespace.
Syntax:
namespace <namespace-name> {
// declarations
}
Formatting Using the ios Members
Formatting Using the ios Members
Each stream has associated with it a set of format flags that control the way
information is formatted. The ios class declares a bitmask enumeration called fmtflags in
which the following values are defined. (Technically, these values are defined within
ios_base, which is a base class for ios.)
To set a flag, use the setf() function. This function is a member of ios.
To unset a flag, use the unsetf() function. This function is a member of ios.
stream.setf(ios::showpos);
Example:
cout.setf(ios::showpoint);
cout.setf(ios::showpos);
cout << 100.0; // displays +100.0
Thank You