C Unit 3
C Unit 3
Unit – 3:- Overloading unary, binary operators – Overloading Friend functions –type conversion –
Inheritance: Types of Inheritance – Single, Multilevel, Multiple, Hierarchal,Hybrid, Multi path
inheritance – Virtual base Classes – Abstract Classes.
4.1 Operator Overloading:-
Assignment Operator =
Unary Operator ++ , -- , -
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. That is to say, We cannot redefine the plus(+)
operator to subtract one value from the other.
4. Overloaded operators follow the syntax rules of the original operators. They cannot be overridden.
6. Binary operators overloaded through a member function take one explicit argument and those which
are overloaded through a friend function take two explicit arguments.
7. When using binary operators overloaded through a member function, the left hand operand must be
an object of the relevant class.
8. Binary arithmetic operators such as +,-,* and / must explicitly return a value. They must not attempt
to change their own arguments.
9. We cannot use “friend” functions to overload certain operators.However, member function can be
used to overload them.
10. Unary operators, overloaded by means of a member function, take no explicit arguments and return
no explicit values,
To define an additional task to an operator, we must specify the relation to the class to which the
operator is applied. This is done with the help of special function called operator function.
Operator functions must be either member function (non- static) or friend function. A basic difference
between that a
Friend Function will have only one argument for unary operators and two arguments for binary
operator.
Member Function have no arguments for unary operator and one argument for binary operator.
a) void operator ++ ( );
b) void operator -- ( );
c) void operator – ( );
d) num operator + ( num ); // binary operator using member function
e) friend num operator * ( int,num ); // binary operator using friend function
f) void operator = ( num ); // Assignment operator
1. Create a class that defines the data type that is to be used in the overloading operation.
2. Declare the operator function
i.e operator op( ) in the public part of the class( either member function or friend function).
Syntax:
Example:-
Explanation:- The operator ++( ) overloads the unary operators ++. When the operator is used with
integer (or) float variables, it‟s value is increased by “1”. In this function, ++ operator preceded each
member variable in class.
In main( ), the statement ++n1 calls the function operator ++ ( ), where n1 is an object of the class num.
o3 = o1 operator-name o2 ;
Both the statements have the same meaning. In the second statement, two objects are passed to the
operator function.
Syntax:
// body of function
As a rule, in overloading of binary operators, the left-hand operand is used to invoke the operator
function and the right-hand operand is passed as an argument.
We can avoid the creation of the temp object by replacing the entire function body by the following
statement: return complex ( ( a + k.a ),( b + k.b ) );
There are various relational operators supported by c++ language, which can be used to compare c++
built-in data types.
For example,
a) Less than ( < )
b) Less than or equal to ( < = )
c) Greater than ( > )
d) Greater than or equal to ( > = )
e) Equal to ( == )
f) Not equal to ( != )
We can overload any of these operators, which can be used to compare the object of the class.
Following example explains how a „ < ’ operator can be overloaded and similar way you can
overload other relational operator.
Syntax:-
return-type class-name :: operator operator-name (arglist)
{
// body of function
}
Example:-
#include<iostream.h>
#include<conio.h>
class num
{
private:
int a;
public:
num(int x)
{
a = x;
}
Output:-
n1 is less than n2
Explanation:- In the above program, from main( ) relational operator function (<) is invoked and
returnthe value. i.e ,n1 object value is 10 and n2 object value is 20. It checks condition and return
corresponding value ( either true = 1 or false = 0 ). Finally it return 1 from operator function to
main() and display true conditi on i.e “n1 is less than n2”.
Type conversion can be done in two ways in C++, one is implicit type conversion, and the second is explicit
type conversion.
Those conversions are done by the compiler itself, called the implicit type or automatic type conversion. The
conversion, which is done by the user or requires user interferences called the explicit or user define type
conversion. Let's discuss the implicit and explicit type conversion in C++.
In the above example, there are two different data type variables, x, and y, where x is an int type, and the y is of
short int data type. And the resultant variable z is also an integer type that stores x and y variables. But the C++
compiler automatically converts the lower rank data type (short int) value into higher type (int) before resulting
the sum of two numbers. Thus, it avoids the data loss, overflow, or sign loss in implicit type conversion of C++.
Order of the typecast in implicit conversion.
The following is the correct order of data types from lower rank to higher rank:
1. bool -> char -> short int -> int -> unsigned int -> long int -> unsigned long int -> long long int -
> float -> double -> long double
Let's create a program to convert smaller rank data types into higher types using implicit type conversion.
Program1.cpp
1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5. // assign the integer value
6. int num1 = 25;
7. // declare a float variable
8. float num2;
9. // convert int value into float variable using implicit conversion
10. num2 = num1;
11. cout << " The value of num1 is: " << num1 << endl;
12. cout << " The value of num2 is: " << num2 << endl;
13. return 0;
14. }
Let's create a program to convert the higher data type into lower type using implicit type conversion.
Program2.cpp
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int num; // declare int type variable
6. double num2 = 15.25; // declare and assign the double variable
7.
8. // use implicit type conversion to assign a double value to int variable
9. num = num2;
10. cout << " The value of the int variable is: " << num << endl;
11. cout << " The value of the double variable is: " << num2 << endl;
12. return 0;
13. }
Output
The value of the int variable is: 15
The value of the double variable is: 15.25
Conversions that require user intervention to change the data type of one variable to another, is called
the explicit type conversion.
In other words, an explicit conversion allows the programmer to manually changes or typecasts the data type
from one variable to another type. Hence, it is also known as typecasting.
Generally, we force the explicit type conversion to convert data from one type to another because it does not
follow the implicit conversion rule.
The explicit type conversion is divided into two ways:
1. Explicit conversion using the cast operator
2. Explicit conversion using the assignment operator
Program to convert float value into int type using the cast operator
Cast operator: In C++ language, a cast operator is a unary operator who forcefully converts one type into
another type.
Let's consider an example to convert the float data type into int type using the cast operator of the explicit
conversion in C++ language.
Program3.cpp
1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5. float f2 = 6.7;
6. // use cast operator to convert data from one type to another
7. int x = static_cast <int> (f2);
8. cout << " The value of x is: " << x;
9. return 0;
DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 13
10. }
Output
The value of x is: 6
Introduction:-
When creating a class, instead of writing completely new data members and member
function, the programmer can designate that the new class should inherit the members of an existing
class. This existing class is called the “Base Class” and the new class is referred as the “Derived Class”.
Definition of Inheritance:-
};
Benefits of Inheritance:-
One of the key benefits of inheritance is to minimize the amount of duplicate code in an
application by sharing common code amongst several subclasses.
Inheritance can also make application code more flexible to change because classes that
inherit from a common superclass can be used interchangeably.
Reusability - facility to use public methods of base class without rewriting the same.
Extensibility - extending the base class logic as per business logic of the derived class.
Data hiding - base class can decide to keep some data private so that it cannot be altered by
the derived class
Overriding -With inheritance, we will be able to override the methods of the base class so
that meaningful implementation of the base class method can be designed in the derived class.
1. Main disadvantage of using inheritance is that the two classes (base and inherited class) get tightly
coupled. This means one cannot be used independent of each other.
2. Also with time, during maintenance adding new features both base as well as derived classes are
required to be changed. If a method signature is changed then we will be affected in both cases
(inheritance & composition).
3. If a method is deleted in the "super class" or aggregate, then we will have to re-factor in case of
using that method.
4. It increased time/effort it takes the program to jump through all the levels of overloaded classes.
Types of Inheritance:-
A class can inherit properties (data) and behaviours (functions) in various levels used for
derivation. In c++, there are six types of inheritance, that are listed below,
B cout<<"ID:"<<id<<endl<<"Name:"<<name;
}
};
fig. Single Inheritance
void main()
Here, A is base class, B is derived class. {
Further no class derived from B. clrscr();
B b; Output:-
b.getdata();
b.display(); Enter ID and Name: 10 Rahul
getch(); ID: 10
} Name: Rahul
{
----- //derived class members
};
#include<iostream.h>
#include<conio.h>
When a class is derived from another derived class
class A
i.e. derived class act as base class. Such types of inheritance {
protected:
is known as multi-level inheritance. int id;
};
A class B : public A
{
protected:
B char name[20];
};
class C : public B
C
{
private:
float height;
Fig. Multi-level inheritance public:
void getdata()
Here, B is derived class from class A(base class). {
cout<<"Enter id,name and height:";
Again B acts as base class to class C, which is derived class. cin>>id>>name>>height;
}
Finally, there is no more derivation from class C.
void display()
{
Syntax:-
cout<<"ID:"<<id<<endl;
class base-class-name1 cout<<"Name:"<<name<<endl;
{ cout<<"Height:"<<height;
----- //class-name1 members }
}; };
class intermediate-base-class-name2 : visibility-mode
base-class-name1 void main()
{ {
----- //class-name2 members clrscr();
}; C c;
class derived-class-name3 : visibility-mode c.getdata();
intermediate-base-class-name2 c.display();
{ getch();
----- //clas-name3 members }
};
Output:-
class B : public A
B D {
protected:
char name[20];
};
C
class C
{
Fig. Hybrid Inheritance protected:
float height;
Here, class B acts as derived class for class A and base class };
for class C. C is derived class form class B and class D. class D : public B,C
{
private:
float weight;
Syntax: public:
void getdata()
class base-class-name1 {
{ cout<<"Enter id,name,height and
----- //class-name1 members weight:";
}; cin>>id>>name>>height>>weight;
}
class intermediate-base-class-name2 : visibility-mode void display()
base-class-name1 {
{ cout<<"ID:"<<id<<endl;
----- //class-name2 members cout<<"Name:"<<name<<endl;
}; cout<<"Height:"<<height<<endl;
class base-class-name3 cout<<"Weight:"<<weight<<endl;
{ }
----- //class-name3 members };
};
class derived-class-name4 : visibility-mode void main() Output:
{
intermediate-base-class-name2,base-class-name3 clrscr()
Enter id,name,height and weight:
D d; 10 Rahul 5.11 78.5
{
d.getdata(); ID: 10
----- //derived-class-name4 members
d.display(); Name: Rahul
};
getch(); Height: 5.11
} Weight: 78.5
When a class is derived from two (or) more classes that are #include<iostream.h>
derived from same base class, such type of inheritance #include<conio.h>
is known as Multi-Path Inheritance.
class A
{
A protected:
int id;
};
B C class B : virtual public A
{
protected:
D char name[20];
};
Let us say the 'child' has two direct base classes „parent1‟ and „parent2‟ which themselves has a
common base class „grandparent‟. The child inherits the traits of „grandparent‟ via two separate
paths. It can also be inherit directly as shown by the broken line. The grandparent is sometimes
referred to as „INDIRECT BASE CLASS‟. Now, the inheritance by the child might cause some
problems. All the public and protected members of „grandparent‟ are inherited into „child‟ twice, first
via „parent1‟ and again via „parent2‟. So, there occurs a duplicacy which should be avoided.
The duplication of the inherited members can be avoided by making common base class as the
virtual base class: for e.g.
class g_parent
{
//Body
};
class parent1: virtual public g_parent
{
// Body
};
When a class is virtual base class, C++ takes necessary care to see that only one copy
of that class is inherited, regardless of how many inheritance paths exists between
virtual base class and derived class. Note that keywords „virtual‟ and „public‟ can be
used in either order.
protected:
int y ;
public:
void get (int) ;
void show (void);
};
void A1 :: get (int a)
{ y = a;}
void A1 :: show (void)
{
cout <<y ;
{
class A2 : Virtual public A
{
protected:
int z ;
public:
void get (int a)
{ z =a;}
void show (void)
{ cout << z;}
};
class A12 : public A1, public A2
{
int r, t ;
public:
void get (int a)
{ r = a;}
void show (void)
{t =x+y+z +r;
cout << “result =” << t ;
}
};
main ( )
{
clrscr ( ) ;
A12 r ;
r.A : : get (3)
; r.A1 : : get
(4) ; r.A2 : :
get (5) ; r.get
(6) ;
r . show ( ) ;
}
4.5 Abstract Class
Abstract Class is a class which contains atleast one Pure Virtual function in it. Abstract classes are
used to provide an Interface for its sub classes. Classes inheriting an Abstract Class must provide
definition to the pure virtual function, otherwise they will also become abstract class.
int main()
{
Base obj; //Compile Time Error Base *b;
Derived d; b = &d;
b->show();
}
Output : Implementation of Virtual Function in Derived class
In the above example Base class is abstract, with pure virtual show() function, hence we cannot
create object of base class.