Você está na página 1de 15

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 - ?:

Operator Overloading Syntax

Implementing Operator Overloading


Operator overloading can be done by implementing a function which can be :

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.

Restrictions on Operator Overloading


Following are some restrictions to be kept in mind while implementing operator overloading.

1. Precedence and Associativity of an operator cannot be changed.


2. Arity (numbers of Operands) cannot be changed. Unary operator remains unary, binary remains
binary etc.
3. No new operators can be created, only existing operators can be overloaded.
4. Cannot redefine the meaning of a procedure. You cannot change how integers are added.

Operator Overloading Examples


Almost all the operators can be overloaded in infinite different ways. Following are some examples
to learn more about operator overloading. All the examples are closely connected.

Overloading Arithmetic Operator


Arithmetic operator are most commonly used operator in C++. Almost all arithmetic operator can be
overloaded to perform arithmetic operation on user-defined data type. In the below example we have
overridden the + operator, to add to Time(hh:mm:ss) objects.

Example: overloading '+' Operator to add two time object


#include< iostream.h>

#include< conio.h>

class time

{
int h,m,s;

public:

time()

h=0, m=0; s=0;

void getTime();

void show()

cout<< h<< ":"<< m<< ":"<< s;

time operator+(time); //overloading '+' operator

};

time time::operator+(time t1) //operator function

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()

cout<<"\n Enter the hour(0-11) ";

cin>>h;

cout<<"\n Enter the minute(0-59) ";

cin>>m;

cout<<"\n Enter the second(0-59) ";

cin>>s;

void main()

clrscr();

time t1,t2,t3;

cout<<"\n Enter the first time ";

t1.getTime();

cout<<"\n Enter the second time ";


t2.getTime();

t3=t1+t2; //adding of two time object using '+' operator

cout<<"\n First time ";

t1.show();

cout<<"\n Second time ";

t2.show();

cout<<"\n Sum of times ";

t3.show();

getch();

Overloading I/O operator

 Overloaded to perform input/output for user defined datatypes.


 Left Operand will be of types ostream& and istream&
 Function overloading this operator must be a Non-Member function because left operand is not
an Object of the class.
 It must be a friend function to access private data members.

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);

cout << t1;

NOTE: When the operator does not modify its operands, the best way to overload the operator is via
friend function.

Example: overloading '<<' Operator to print time object


#include< iostream.h>

#include< conio.h>

class time

int hr,min,sec;

public:

time()

hr=0, min=0; sec=0;


}

time(int h,int m, int s)

hr=h, min=m; sec=s;

friend ostream& operator << (ostream &out, time &tm); //overloading '<<' operator

};

ostream& operator<< (ostream &out, time &tm) //operator function

out << "Time is " << tm.hr << "hour : " << tm.min << "min : " << tm.sec << "sec";

return out;

void main()

time tm(3,15,45);

cout << tm;

Output
Time is 3 hour : 15 min : 45 sec

Overloading Relational operator


You can also overload Relational operator like == , != , >= , <= etc. to compare two user-defined
object.

Example
class time

int hr,min,sec;

public:

time()

hr=0, min=0; sec=0;

time(int h,int m, int s)


{

hr=h, min=m; sec=s;

friend bool operator==(time &t1, time &t2); //overloading '==' operator

};

bool operator== (time &t1, time &t2) //operator function

return ( t1.hr == t2.hr &&

t1.min == t2.min &&

t1.sec == t2.sec );

Copy constructor Vs. Assignment operator


Assignment operator is used to copy the values from one object to another already existing
object. For example
time tm(3,15,45); //tm object created and initialized

time t1; //t1 object created

t1 = tm; //initializing t1 using tm

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

time t1(tm); //t1 object created and initialized using tm object

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:

 Null pointers can be converted to pointers of any type


 Pointers to any type can be converted to void pointers.
 Pointer upcast: pointers to a derived class can be converted to a pointer of
an accessible and unambiguous base class, without modifying
its const or volatile qualification.

Implicit conversions with classes


In the world of classes, implicit conversions can be controlled by means of three member functions:

 Single-argument constructors: allow implicit conversion from a particular type to initialize an


object.
 Assignment operator: allow implicit conversion from a particular type on assignments.
 Type-cast operator: allow implicit conversion to a particular type.

For example:

1 // implicit conversion of classes: Edit


2 #include <iostream> &
3 using namespace std; Run
4
5 class A {};
6
7 class B {
8 public:
9 // conversion from A (constructor):
10 B (const A& x) {}
11 // conversion from A (assignment):
12 B& operator= (const A& x) {return
13 *this;}
14 // conversion to A (type-cast
15 operator)
16 operator A() {return A();}
17 };
18
19 int main ()
20 {
21 A foo;
22 B bar = foo; // calls constructor
23 bar = foo; // calls assignment
24 foo = bar; // calls type-cast
operator
return 0;
}

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

as inheritance. It is one of the fundamental features of object-oriented programming.

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

class subclass_name : superclass_name

// data members

// methods

Real Life Example of Inheritance in C++

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

class and they are visible in student class logically.

Advantage of inheritance

If we develop any application using this concept than that application have following advantages,

 Application development time is less.

 Application take less memory.

 Application execution time is less.

 Application performance is enhance (improved).

 Redundancy (repetition) of the code is reduced or minimized so that we get consistence results

and less storage cost.

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.

Intermediate base classes

An intermediate base class is one in one context with access derived class and in another context same

class access base class.


Hence all the above three inheritance types are supported by both classes and interfaces.

Multiple inheritance

In multiple inheritance there exist multiple classes and singel derived class.

Hybrid inheritance

Combination of any inheritance type


Inheriting the feature from base class to derived class

In order to inherit the feature of base class into derived class we use the following syntax

Syntax

class classname-2 : classname-1

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

improves the functionality of derived class.


Example of Inheritance in C++

#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

Enter employee salary: 50000

Employee salary: 50000

Você também pode gostar