Operator Overloading
Operator Overloading
Overloaded operator is used to perform operation on user-defined data type. For example '+'
operator can be overloaded to perform addition on various data types, like for Integer,
String(concatenation) etc.
Almost any operator can be overloaded in C++. However there are few operator which can not be
overloaded. Operator that are not overloaded are follows
scope operator - ::
sizeof
member selector - .
member pointer selector - *
ternary operator - ?:
1. Member Function
2. Non-Member Function
3. Friend Function
Operator overloading function can be a member function if the Left operand is an Object of that
class, but if the Left operand is different, then Operator overloading function must be a non-member
function.
Operator overloading function can be made friend function if it needs access to the private and
protected members of class.
#include< conio.h>
class time
{
int h,m,s;
public:
time()
void getTime();
void show()
};
time t;
int a,b;
a=s+t1.s;
t.s=a%60;
b=(a/60)+m+t1.m;
t.m=b%60;
t.h=(b/60)+h+t1.h;
t.h=t.h%12;
return t;
void time::getTime()
cin>>h;
cin>>m;
cin>>s;
void main()
clrscr();
time t1,t2,t3;
t1.getTime();
t1.show();
t2.show();
t3.show();
getch();
You have seen above that << operator is overloaded with ostream class object cout to print
primitive type value output to the screen. Similarly you can overload << operator in your class to print
user-defined type to screen. For example we will overload << in time class to display time object
using cout.
time t1(3,15,48);
NOTE: When the operator does not modify its operands, the best way to overload the operator is via
friend function.
#include< conio.h>
class time
int hr,min,sec;
public:
time()
friend ostream& operator << (ostream &out, time &tm); //overloading '<<' operator
};
out << "Time is " << tm.hr << "hour : " << tm.min << "min : " << tm.sec << "sec";
return out;
void main()
time tm(3,15,45);
Output
Time is 3 hour : 15 min : 45 sec
Example
class time
int hr,min,sec;
public:
time()
};
t1.sec == t2.sec );
Copy constructor is a special constructor that initializes a new object from an existing object.
time tm(3,15,45); //tm object created and initialized
Type conversions
Implicit conversion
Implicit conversions are automatically performed when a value is copied to a compatible type. For
example:
1 short a=2000;
2 int b;
3 b=a;
Here, the value of a is promoted from short to int without the need of any explicit operator. This is
known as a standard conversion. Standard conversions affect fundamental data types, and allow the
conversions between numerical types (short to int, int to float, double to int...), to or
from bool, and some pointer conversions.
Converting to int from some smaller integer type, or to double from float is known as promotion,
and is guaranteed to produce the exact same value in the destination type. Other conversions between
arithmetic types may not always be able to represent the same value exactly:
If a negative integer value is converted to an unsigned type, the resulting value corresponds to
its 2's complement bitwise representation (i.e., -1 becomes the largest value representable by
the type, -2 the second largest, ...).
The conversions from/to bool consider false equivalent to zero (for numeric types) and to null
pointer (for pointer types); true is equivalent to all other values and is converted to the
equivalent of 1.
If the conversion is from a floating-point type to an integer type, the value is truncated (the
decimal part is removed). If the result lies outside the range of representable values by the type,
the conversion causes undefined behavior.
Otherwise, if the conversion is between numeric types of the same kind (integer-to-integer or
floating-to-floating), the conversion is valid, but the value is implementation-specific (and may
not be portable).
Some of these conversions may imply a loss of precision, which the compiler can signal with a warning.
This warning can be avoided with an explicit conversion.
For non-fundamental types, arrays and functions implicitly convert to pointers, and pointers in general
allow the following conversions:
For example:
The type-cast operator uses a particular syntax: it uses the operator keyword followed by the
destination type and an empty set of parentheses. Notice that the return type is the destination type
and thus is not specified before the operator keyword.
Keyword explicit
On a function call, C++ allows one implicit conversion to happen for each argument. This may be
somewhat problematic for classes, because it is not always what is intended. For example, if we add the
following function to the last example:
void fn (B arg) {}
This function takes an argument of type B, but it could as well be called with an object of type A as
argument:
fn (foo);
This may or may not be what was intended. But, in any case, it can be prevented by marking the
affected constructor with the explicit keyword:
1 // explicit: Edit & Run
2 #include <iostream>
3 using namespace std;
4
5 class A {};
6
7 class B {
8 public:
9 explicit B (const A& x) {}
10 B& operator= (const A& x) {return *this;}
11 operator A() {return A();}
12 };
13
14 void fn (B x) {}
15
16 int main ()
17 {
18 A foo;
19 B bar (foo);
20 bar = foo;
21 foo = bar;
22
23 // fn (foo); // not allowed for explicit ctor.
24 fn (bar);
25
26 return 0;
27 }
Additionally, constructors marked with explicit cannot be called with the assignment-like syntax; In
the above example, bar could not have been constructed with:
B bar = foo;
Type-cast member functions (those described in the previous section) can also be specified
as explicit. This prevents implicit conversions in the same way as explicit-specified constructors
do for the destination type.
Inheritance in C++
The process of obtaining the data members and methods from one class to another class is known
Important points
In the inheritance the class which is give data members and methods is known as base or super
or parent class.
The class which is taking the data members and methods is known as sub or derived or child
class.
Syntax
// data members
// methods
The real life example of inheritance is child and parents, all the properties of father are inherited by his son.
Diagram
In the above diagram data members and methods are represented in broken line are inherited from faculty
Advantage of inheritance
If we develop any application using this concept than that application have following advantages,
Redundancy (repetition) of the code is reduced or minimized so that we get consistence results
Tpyes of Inheritance
Based on number of ways inheriting the feature of base class into derived class it have five types they are:
Single inheritance
Multiple inheritance
Hierarchical inheritance
Multiple inheritance
Hybrid inheritance
Single inheritance
In single inheritance there exists single base class and single derived class.
Multiple inheritances
In multiple inheritances there exists single base class, single derived class and multiple intermediate base
classes.
Single base class + single derived class + multiple intermediate base classes.
An intermediate base class is one in one context with access derived class and in another context same
Multiple inheritance
In multiple inheritance there exist multiple classes and singel derived class.
Hybrid inheritance
In order to inherit the feature of base class into derived class we use the following syntax
Syntax
variable declaration;
method declaration;
Explanation
classname-1 and classname-2 represents name of the base and derived classes respectively.
: is operator which is used for inheriting the features of base class into derived class it
#include<iostream.h>
#include<conio.h>
class employee
{
public:
int salary;
};
class developer : public employee
{
employee e;
public:
void salary()
{
cout<<"Enter employee salary: ";
cin>>e.salary; // access base class data member
cout<<"Employee salary: "<<e.salary;
}
};
void main()
{
clrscr();
developer obj;
obj.salary();
getch();
}
Output