Unit 3
Unit 3
OPERATIOR OVERLOADING
1. Create a class that defines the data type that is to be used in the overloading
operation .
2. Declare the operator function operator op ( ) in the public part of the class .
It may be either a member function or a friend function .
3. Define the operator function to implement the required operations
Overloaded operator functions can be invoked by expressions such as
op X or X op (for unary operators)
x op y (for binary operators )
The member function requires one argument for binary operators and no argument for
unary operators.
A friend function requires one argument for unary operators and two for binary
operators.
EXAMPLE PROGRAM:-
Class num }
{ void operator – ( )
int a; {
public: a=-a;
num(int x) }
{ void show ( )
a=x; {
cout<<”a=”<<a; num o(6);
} -o;
}; o.show ( );
void main ( ) }
{
OUTPUT:-
a = -6
In above example class num contains two member functions show() and operator –()
and one parameterized constructor. The constructor is used to initialize object.
The show() displays the contents of the member variables.
The operator –() overloads the unary operator -. This operation change the sign of the
variables.
In function main(), the statement –o calls the function operator –(), where o is an
object of the class num.
RULES FOR OVERLOADING OPERATORS
1. only existing operators can be overloaded . New operators cannot be created
2. The overloaded operator must have at least one operand that is of user-
defined type.
3. we cannot change the basic meaning of an operator
4. There are some operators that cannot be overloaded
5. We cannot use friend functions to overload certain operators
6. unary operators , overloaded by means of a member functions , take no
explicit arguments and return no explicit values .
7. Binary operators overloaded through a member function take one explicit
argument and those which are overloaded through a friend function take
two explicit arguments
8. When using binary operators overloaded through a member function , the
left hand operand must be an object of the relevant class
9. Binary arithmetic operators such as +,-,* and / must explicitly return a
value.
10. We cannot overload the operator for built in data types.
OVERLOADING UNARY OPERATORS
The operator ++ , -- and - are unary operators . The unary operator ++ and --
can be used as prefix or suffix with the functions . These operators have only single
operand .
The general form is
return type operator operator symbol(parameters)
{
Function body
}
Operator functions are declared in the class using prototypes as follows :
For example:
vector operator+(vector);
The process of overloading involves the following steps :
1. Create a class that defines the data type that is to be used in the overloading
operation .
2. Declare the operator function operator op ( ) in the public part of the class .
It may be either a member function or a friend function .
3. Define the operator function to implement the required operations
Overloaded operator functions can be invoked by expressions such as
op X or X op (for unary operators)
}
EXAMPLE PROGRAM:-
}
Class num void show ( )
{ {
int a; cout<<”a=”<<a;
public: }
num(int x) };
{ void main ( )
a=x; {
} num o(6);
void operator – ( ) -o;
{ o.show ( );
a=-a; }
OUTPUT:-
a = -6
In above example class num contains two member functions show() and operator –()
and one parameterized constructor. The constructor is used to initialize object.
The show() displays the contents of the member variables.
The operator –() overloads the unary operator -. This operation change the sign of the
variables.
In function main(), the statement –o calls the function operator –(), where o is an
object of the class num.
OVERLOADING BINARY OPERATORS:-
Overloading with a single parameter is called as binary operator overloading .
Binary operators are overloaded by using member function and friend functions .
The general form is
return type operator operator symbol(parameters)
{
Function body
}
Operator functions are declared in the class using prototypes as follows :
For example:
vector operator+(vector);
The process of overloading involves the following steps :
1. Create a class that defines the data type that is to be used in the overloading
operation .
2. Declare the operator function operator op ( ) in the public part of the class .
It may be either a member function or a friend function .
3. Define the operator function to implement the required operations
Overloaded operator functions can be invoked by expressions such as
x op y (for binary operators )
The member function requires one argument for binary operators and no argument for
unary operators.
A friend function requires one argument for unary operators and two for binary
operators.
EXAMPLE PROGRAM:-
#include<iostream.h>
class num
{
int a,b;
public :
num (x,y)
{
a=x; b=y;
}
num operator + (num t)
{
num t ;
t.a = a+t.a
t.b = b+t.b
return ( num );
}
void show ( )
{
cout<<”A”<<a<<”B=”<<b;
}
};
void main ( )
{
num x (10,5);
num y (20,10);
z = x+y ;
cout<<”OBJECT X “;
x . show ( );
cout<<”OBJECT y”;
y.show ( );
cout<<”OBJECT z “;
z . show ( );
}
OUTPUT :-
OBJECT X
a = 10 b=5
OBJECT Y
a = 20 b = 10
OBJECT Z
a = 30 b = 15
OVERLOADING FRIEND FUNCTION
The difference between member function and friend function is that the member function takes
arguments explicitly . A friend function requires one argument for unary *operators and two for
binary
Syntax:-
Friend return- type operator operator-symbol (variable 1 , variable 2)
{
statement 1;
statement 2;
}
The keyword friend precedes function prototype declaration . It must be written inside the class . The
function can be defined inside or outside the class . The arguments used in friend functions are
generally objects of the friend classes .
The process of overloading involves the following steps :
1. Create a class that defines the data type that is to be used in the overloading operation .
2. Declare the operator function operator op ( ) in the public part of the class . It may be
either a member function or a friend function .
3. Define the operator function to implement the required operations
EXAMPLE PROGRAM:-
(1) Overloading unary operators using friend functions
Class one
{
int a;
public:
one()
{
a=0;
}
one(int x)
{
a=x;
}
friend one operator – ( one ob )
{
ob.a=-ob.a;
return(ob);
}
void show ( )
{
cout<<”a=”<<a;
}
};
void main ( )
{
one o(6),o1;
o1=-o;
o1.show ( );
}
Output:
A = -6;
In the above program operator - is overloaded using friend function. The operator function defined
as friend. The statement o1=-o invokes the operator function.
Class one
{
int a;
public:
one()
{
a=0;
}
one(int x)
{
a=x;
}
friend one operator – ( int a,one ob )
{
ob.a=-a * ob.a;
return ob
}
void show ( )
{
cout<<”a=”<<a;
}
};
void main ( )
{
Chap. 8 OPERATOR OVERLOADING AND TYPE CONVERSIONS
one o(6),o1;
o1=2*o;
o1.show ( );
}
Output:
A = 12;
In the above program operator -* is overloaded using friend function. The operator function defined
as friend. The statement o1=2 *-o invokes the operator function.
TYPE CONVERSION
The complier has no idea about the user-defined data types and about their conversion to
other data types . The programmer should write the routines thatconvrt basic data types to user-
defined data types or vice-versa .
There are three types :
(1) Conversion from basic data type to user-defined data type (class type) .
(2) Conversion . from class type to basic data type .
(3) Conversion from one class type to another class type .
SAMPLE PROGRAM:-
#include<iostream.h
#include<conio.h>
class data
{
int x;
float f;
public:
data ( )
{
x=0;
f=0;
}
data ( float m)
{
x=2;
f=m;
}
void show ( )
{
cout<<”\n x= “<<x<< “ f = “<<f;
}
};
int main( )
{
clrscr ( );
data z;
z=1; conversion from basic type to class type
z.show ( );
}
OUTPUT:-
X=2 f=1
In the above program, when z=1 ,the constructor with float argument is invoked, thus the conversion
from basic to class type is carried out.
CONDITION:-
(1) The conversion function should not have any argument
(2) Do not mention return type
(3) It should be a class member function .
For example
J=a where a is an object and j is an interger, thus the coversion from class type to basic type is
carried out.
SAMPLE PROGRAM:-
#include <iostream.h>
#include<conio.h>
class data
{
int x;
float f;
public :
data ( )
{
x=0;
f=0;
}
operator int ( )
{
return (x);
}
operator float ( )
Chap. 8 OPERATOR OVERLOADING AND TYPE CONVERSIONS
{
return f ;
}
data ( float m)
{
x=2;
f=m ; conversion from class type to basic type
}
};
int main ( )
{
clrscr ( );
int j;
float f;
data a;
a=5.5;
j =a; the function operator int() is invoked
f=a; the function operator float() is invoked
In the above program , the class contains two member functions operator int() and operator float().
Both these functions are able to convert data types from class to basic.
For example
X=A; Here X is an object of class XYZ and A is an object of class ABC. The class ABC data type is
converted to class XYZ.
Sample Program
#include <iostream.h>
#include <conio.h>
class minutes
{
int m;
public:
minutes()
{
m=240;
}
get()
{
return(m);
}
void show()
{
cout<< “Minutes =”<<m;
}
};
class hours
{
int h;
public:
void operator =(minutes x)
{
h=x.get()/60;
}
void show()
{
cout<<”Hours =”<<h;
}
};
void main()
{
minutes minute
hours hour;
hour=minute; conversion from one class type to another class type
minute.show();
hour.show();
}
Output:
Minutes=240
Hours=4
In the above program , converts minutes to hours, The equation hour=minute invokes the operator
function.
Chap. 8 OPERATOR OVERLOADING AND TYPE CONVERSIONS
Increment Operator Overloaded
The operator ++ , -- and - are unary operators . The unary operator ++ and -- can be used as
prefix or suffix with the functions . These operators have only single operand .
vector operator+(vector);
The process of overloading involves the following steps :
1. Create a class that defines the data type that is to be used in the overloading operation .
2. Declare the operator function operator op ( ) in the public part of the class . It may be
either a member function or a friend function .
3. Define the operator function to implement the required operations
EXAMPLE PROGRAM:-
class num
{
int a;
public:
num(int x)
{
a=x;
}
void operator ++ ( )
{
a=++a;
}
void show ( )
{
cout<<”a=”<<a;
}
};
void main ( )
{
num o(6);
++o;
o.show ( );
}
OUTPUT:-
a=7
In above example class num contains two member functions show() and operator ++() and one
parameterized constructor. The constructor is used to initialize object.
The show() displays the contents of the member variables.
The operator ++() overloads the unary operator++. This operation ,the value of variables increment
by 1.
In function main(), the statement ++o calls the function operator ++(), where o is an object of the
class num.
Summary
Operator Overloading
use the resulting operator with objects of its class as its operands is called operator
overloading.
Only existing operators can be overloaded . New operators cannot be created
EXERCISE QUESTIONS
The procedure of creating a new class from one or more existing classes is termed as
inheritance.
The public members of a class can be accessed by objects directly outside the class.
The private members of the class can only be accessed by public member function of the same class.
The protected access specifier is same as private. The only difference is that it allows its derived
classes to access protected members directly without member functions.
The base class is called as super class, parent or ancestor and derived class as sub class, child or
descendent.
The colon indicates that the derived-class-name is derived from the base-class-name.The visibility-
mode is optional and,if present, may be either private or public.The default visibility-mode is private
(1) Class B :public A //public derivation
{
// members of class B
};
When a base class is privately inherited by a derived class, ‘public members’ of the base class
become ‘private members’ of the derived class.
Chap. 9 Inheritance
When the base class is publicly inherited , ‘public members’ of the base class become ‘public
members’ of the derived class.
(A) When a classes derived by private derivation, public members of the base class are private in the
derived class.
When a classes derived by protected derivation, public members of the base class are
protected in the derived class.
C friend function
(A) The class member function can access the private , protected and public members .
(B) The derived class member function cannot access the private members of the base class
directly . however , the private members can be accessed using member functions of the base
class .
(C) The friend function of a friendclass can access the private and protected members .
(D) The member function of a friend
ADVANTAGES OF INHERITANCE:-
(1) The most frequent use of inheritance is for deriving classes , which provides
reusability .The existing classes remain unchanged . By reusability , the development
time of software is reduced
(2) The derived classes extend the properties of base classes to generate more dominant
object.
(3) The same base classes can be used by a number of derived classes in class hierarchy.
(4) When a class is derived from more than one class, all the derived classes have the same
properties as that of base classes.
DISADVANTAGES OF INHERITANCE:-
(1) Use of inheritance makes a program more complicated .
(2) Invoking member functions using objects create more compiler overheads .
(3) In class hierarchy various data elements remain unused , the memory allocated to them
is not utilized
Sample Program
#include <stream.h>
class B
{
public:
int a,b;
void get_ab()
{
cout <<”Enter two number “;
cin>>a>>b;
}
};
class D:private B
{
int c;
public:
void display()
{
c=a*b;
cout <<”C =”<<c;
}
};
void main()
{
D d;
d.get_ab();
d.display();
}
Chap. 9 Inheritance
Output :
Enter two number 4,6
C = 24
In the above program the class D derived from class B . The statement class D:private B
defines the derived class D and The derived class D can access the public member of base class
B by private.
TYPES OF INHERITANCE
(3)HIERARCHICAL INHERITANCE:-
When a single base class is used for derivation of two or more classes , it is known as
hierarchical inheritance .
X Y Z
Where W is only one base class. X,Y and Z are derived classes.
Z
Where X is a base class. Y is derived from X. Further, Z is derived from Y.
Y Z
where class Y derived from class X and Class W derived from base class Y and Z.
Chap. 9 Inheritance
X Y
Where The classes X and Y are derived from W base class. Class Z is derived from X and Y.
For example
#include<iostream.h>
#include<constream.h>
class A1 //base class
{
protected :
int a;
};
class A2 : public A1 //derivation first level
{
protected :
int b;
};
class A3 : public A2 //derivation second level
{
protected :
int c;’
void get( ) // reads data
{
cin>>a>>b>>c;
}
SINGLE INHERITANCE
When only one class is derived from a single base class such derivation of a class is known as single
inheritance.
DEFINING DERIVED CLASSES :-
The colon indicates that the derived-class-name is derived from the base-class-name.The visibility-
mode is optional and,if present, may be either private or public.The default visibility-mode is private
The new class is termed as derived class and the old class is called as base class.
The newly created class receives entire characteristics from its base class.
In single inheritance , there are only one base class and derived class .
Class B Base class
Sample Program
#include <stream.h>
class B
{
public:
int a,b;
void get_ab()
Chap. 9 Inheritance
{
cout <<”Enter two number “;
cin>>a>>b;
}
};
class D:private B
{
int c;
public:
void display()
{
c=a*b;
cout <<”C =”<<c;
}
};
void main()
{
D d;
d.get_ab();
d.display();
}
Output :
Enter two number 4,6
C = 24
In the above program the class D derived from class B . The statement class D:private B
defines the derived class D and The derived class D can access the public member of base class
B by private.
MULTILEVEL INHERITANCE
The procedure of deriving a class from derived class is named as multilevel inheritance.
DEFINING DERIVED CLASSES :-
The general form of defining a derived class is :
Class derived-class-name : visibility-mode base-class-name
{
………….//
………….// members of derived class
…………..//
};
The colon indicates that the derived-class-name is derived from the base-class-name.The visibility-
mode is optional and,if present, may be either private or public.The default visibility-mode is private
Class A3 is derived from class A2 . The class A2 is derive from class A1. The class A3 is derived
class
EXAMPLE PROGRAM:
#include<iostream.h>
#include<constream.h>
class A1 //base class
{
protected :
int a;
};
class A2 : public A1 //derivation first level
{
protected :
int b;
};
class A3 : public A2 //derivation second level
{
protected :
int c;
void get( ) // reads data
{
cin>>a>>b>>c;
}
Chap. 9 Inheritance
MULTIPLE INHERITANCE
When a class is derived from more than one class then this type of inheritance is called as
multiple inheritance .
The general form is
Class D : visibility B-1,visibility B-2……
{
…….
…….(body of D)
…….
};
Where ,visibility may be either public or private. The base classes are separated by commas.
EXAMPLE PROGRAM:-
#include<iostream.h>
#include<constream.h>
class A { protected : int a ;}; //class A declaration
class B { protected : int b ; }; //class B declaration
class C { protected : int c ; }; //class C declaration
class D { protected : int d ;}; //class D declaration
class E : public A,B,C,D //multiple derivation
{
int e ;
public :
void getdata( )
{
cout<<”\n Enter values of a,b,c & d&e:”;
cin>>a>>b>>c>>d>>e;
}
void showdata( )
{
cout <<”\n a=”<<a<<”b=”<<b<<”c=”<<c<<”d=”<<d<<”e=”<<e;
}
};
void main( )
{
clrscr( );
E x;
x.getdata( ); //reads data
x.showdata( ); //displays data
}
OUTPUT:
Enter values of a,b,c &d&e :1 2 4 8 16
a = 1 b =2 c =4 d =8 z =16
Class A
Derived class
HIERARCHICAL INHERITANCE
The colon indicates that the derived-class-name is derived from the base-class-name.The visibility-
mode is optional and,if present, may be either private or public.The default visibility-mode is private
EXAMPLE PROGRAM:
#include<iostream.h>
#include<constream.h>
class red
{
public :
red ( ) { cout<<”red”;};
};
class yellow:public red
Chap. 9 Inheritance
{
public :
yellow ( ) { cout<<”+yellow=orange”;}
};
class blue:public red
{
public :
blue ( ) { cout<<”+blue=violet”;}
};
void main ( )
{
clrscr ( );
yellow obj;
endl(cout);
blue obj1
endl(cout);
OUTPUT:-
Base class
Class red
HYBRID INHERITANCE:-
Combine with multiple and multilevel inheritance is called hybrid inheritance .
The colon indicates that the derived-class-name is derived from the base-class-
name.The visibility-mode is optional and,if present, may be either private or public.The default
visibility-mode is private
EXAMPLE PROGRAM:-
#include<iostream.h>
#include<constream.h>
class PLAYER
{
protected :
char name[15];
char gender;
int age;
};
class PHYSIQUE : public PLAYER
{
protected:
float height ;
float weight ;
};
class LOCATION
{
protected :
char city [10];
char pin[7];
};
class GAME : public PHYSIQUE , LOCATION
{
protected :
char game[15];
public:
void getdata( )
{
cout<<”Enter following information\n”;
cout<<”Name : “;cin>>name;
cout<<”Gender : “;cin>>gender;
cout<<”Age : “;cin>>age;
cout<<”Height : “;cin>>height;
cout<<”Weight : “;cin>>weight;
cout<<”City : “;cin>>city;
cout<<”Pincode : “;cin>>pincode;
cout<<Game : “;cin>>game;
}
Chap. 9 Inheritance
void show ( )
{
cout<<”\n Entered informatiom”;
cout<<”Name : “;cout<<name;
cout<<”Gender : “;cout<<gender;
cout<<”Age : “;cout<<age;
cout<<”Height : “;cout<<height;
cout<<”Weight : “;cout<<weight;
cout<<”City : “;cout<<city;
cout<<”Pincode : “;cout<<pincode;
cout<<Game : “;cout<<game;
}
};
int main( )
{
clrscr ( );
GAME G ;
G.getdata ( );
G.show ( );
return 0;
}
OUTPUT:-
Enter the following information
Name : mahesh
Gender : M
Age : 25
Height : 4.9
Weight : 55
City : nanded
Pincode : 431603
Game : cricket
Entered information
Name : mahesh
Gender : M
Age : 25
Height : 4.9
Weight : 55
City : nanded
Pincode :431603
Game : cricket
LOCATION PLAYER
PYHSIQUE
GAME
The class PHYSIQUE derived from class PLAYER. The class GAME derived from the class
LOCATION and PHYSIQUE.
MULTI-PATH INHERITANCE
When a class is derived from two or more classes , which are derived from the same base
class such type of inheritance is known as multi-path inheritance . multi-path inheritance consists
of many types of inheritances such as multiple , multilevel and hierarchical
DEFINING DERIVED CLASSES :-
The general form of defining a derived class is :
Class derived-class-name : visibility-mode base-class-name
{
………….//
………….// members of derived class
…………..//
};
The colon indicates that the derived-class-name is derived from the base-class-name.The visibility-
mode is optional and,if present, may be either private or public.The default visibility-mode is private
For example
class A1
{
protected:
int a1;
};
class A2 : public A1
{
protected:
int a2;
};
Chap. 9 Inheritance
class A3:public A1
{
protected:
int a3;
};
class A4:public A2,A3
{
int a4;
};
Class A1
Class A2 Class A3
Class
A4
A1 is a base class. The classes A2 and A3 are derived from A1 base class. The class A4 is derived
from A2 and A3. A2 and A3 have same copies of members inherited from A1. Here ambiguity is
generated. Hence virtual keyword is used to avoid ambiguity.
The duplication of inherited members due to these multiple paths can be avoided by
making the common base class (ancestor class) as virtual base class
When a class is made a virtual base class , C++ takes necessary care to see that only one copy of
that class is inherited
C++ provides the keyword virtual . The keyword virtual declares the specified classes virtual .
For example
Class A1
{
protected :
int a1;
};
When classes are declared as virtual , the compiler takes necessary precaution to avoid
duplication of member variables .
EXAMPLE PROGRAM:-
#include<iostream.h>
#include<conio.h>
class A1
{
protected :
int a1;
};
void get( )
{
cout <<”Enter values for a1,a2,a3,and a4:”;
cin>>a1>>a2>>a3>>a4;
}
void put( )
{
cout<<”a1=”<<a1<<”a2=”<<a2<<”a3=”<<a3<<”a4=”<<a4;
}
};
void main ( )
{
clrscr( );
A4.a( );
a.get( ); // reads data
a.put( ); // displays data
}
OUTPUT:-
Enter values for a1,a2,a3 and a4 : 5 8 7 3
a1 = 5 a2 = 8 a3 = 7 a4 = 3
In the above program the classes A2 and A3 are derived from class A1. While deriving these two
classes. The class A1 is declared as virtual.
ABSTRACT CLASSES
When a class is not used for creating objects it is called as abstract class .
The abstract class can act as a base class only.
It allows a base on which several levels of inheritance can be created .
The base classes act as foundation of class hierarchy .
An abstract class gives a skeleton or structure , using which other classes are shaped .
For example
#include<iostream.h>
#include<constream.h>
class red
{
public :
red ( ) { cout<<”red”;};
};
class yellow:public red
{
public :
yellow ( ) { cout<<”+yellow=orange”;}
};
class blue:public red
{
public :
blue ( ) { cout<<”+blue=violet”;}
};
void main ( )
{
clrscr ( );
yellow obj;
endl(cout);
blue obj1
endl(cout);
}
OUTPUT:-
Base class
Class red
Summary
The procedure of creating a new class from one or more existing classes is termed as
inheritance.
There are six types of Inheritance
o Single inheritance
o Multiple inheritance
o Hierarchical inheritance
o Multilevel inheritance
o Hybrid inheritance
o Multi-path inheritance
When a class is made a virtual base class , C++ takes necessary care to see that only one copy of that
class is inherited
When a class is not used for creating objects it is called as abstract class .
Chap. 9 Inheritance
EXERCISE