Unit 3 Notes
Unit 3 Notes
[3 Semester]
rd
By,
Vinni Sharma
Associate Professor
BIT Durg
1
Unit III
Operator Overloading
and
Inheritance
Operator Overloading
C++ has the ability to provide the operators with a special meaning for a
data type, this ability is known as operator overloading.
For example, we can overload an operator ‘+’ in a class like String so that
we can concatenate two strings by just using +.
Some examples where arithmetic operators may be overloaded are
Complex Numbers, Fractional Numbers, Big Integers, etc.
Unary operators, overloaded by means of a member function, take
no explicit argument and return no explicit values.
Binary operators overloaded through a member function take one
explicit argument
Operator Overloading contd.
We can overload all the C++ operators except the following:
• Class members access operator (. and .*)
• Scope resolution operator (: :)
• Size operator(sizeof)
• Condition operator (? :)
Syntax:
return-type class-name :: operator op( arg-list) { function body }
Write a C++ program to show Overloading of Unary
operators increment “++” and decrement “--”
void operator --()
#include<iostream.h> {
#include<conio.h> a=--a;
class complex b=--b;
{ }
int a,b; void display()
public: {
complex(){} cout<<a<<"+\t"<<b<<"i"<<endl;
void getvalue() }
{ };
cout<<"Enter the real and imag void main()
part:"; {
cin>>a>>b; clrscr();
} complex obj;
void operator ++ () obj.getvalue();
{ obj++;
a=++a; cout<<"Increment Complex Number\n";
b=++b; obj.display();
} obj--;
cout<<"Decrement Complex Number\n";
obj.display();
getch();
}
Write a C++ program to explain Overloading of
Binary operator “+” to add two complex nos.
#include<iostream.h>
# include<conio.h>
class complex {
int main()
private:
{
int real, imag;
cout<<“Enter the real and imag part of 1st complex no.: ”;
public:
cin>>a>>b;
complex(int r = 0, int i =0) {real = r; imag = i;}
cout<<“Enter the real and imag part of 2nd complex no.: ”;
// This is automatically called when '+' is used with
cin>>c>>d;
// between two Complex objects
complex c1(a,b), c2(c,d);
complex operator + (complex obj)
complex c3 = c1 + c2; // An example call to "operator+“
{
cout<<“The two complex nos and their sum are: ”
complex res;
c1.print();
res.real = real + obj.real;
c2.print();
res.imag = imag + obj.imag;
c3.print();
return res;
}
}
void print()
{
cout <<“\n”<< real << " + i" << imag << endl; }
};
Operator Overloading Contd.
The process of overloading involves the following steps:-
• Create a class that defines the data type that is used in the overloading operation.
• Declare the operator function operator op() in the public part of the class
• It may be either a member function or friend function.
• Define the operator function to implement the required operations
Note: Overloading an operator should not change its basic meaning. For example assume the +
operator can be overloaded to subtract two objects. But the code becomes unreachable.
Manipulation of Strings using
Operator Overloading
• There are no direct operator that could act upon the strings or
manipulate the strings.
• Although there are these limitations exist in C++, it permits us to
create our own definitions of operators that can be used to
manipulate the strings very much similar to the decimal number.
• We can manipulate strings by operator overloading.
• String Manipulation in C++ uses many string functions which we can
use to manipulate the strings, therefore we have to include string
library (#include <string.h>).
Write a C++ program to explain Overloading of Binary
operator “+” to concatenate two strings.
#include<iostream.h>
#include<string.h>
void main()
# include <conio.h>
{
class string
clrscr();
{
string s1, s2, s3;
private:
s1.input();
char str[25];
s2.input();
public:
cout<<"\n First String ";
void input()
s1.display(); //Displaying First String
{
cout<<"\n Second String ";
cout<<"\n Enter String : ";
s2.display(); //Displaying Second String
cin>>str;
s3=s1+s2; //Strings are concatenated directly using '+' operator
}
cout<<"\n Concatenated String : ";
void display()
s3.display();
{
getch();
cout<<“The String is:” <<str;
}
}
string operator +(string x) //Concatenating String function defined
{
string s;
strcat(str,x.str);
strcpy(s.str,str);
return s;
}
};
Write a C++ program to explain Overloading of Binary
operator “==” to compare two strings.
#include<iostream.h>
#include<string.h>
# include <conio.h> void main()
class string {
{ clrscr();
private: string s1, s2;
char str[25]; s1.input();
public: s2.input();
void input() cout<<"\n First String ";
{ s1.display(); //Displaying First String
cout<<"\n Enter String : "; cout<<"\n Second String ";
cin>>str; s2.display(); //Displaying Second String
} if (s1==s2) //Strings compared directly using ‘==' operator
void display() cout<<"\n Strings are equal ";
{ else
cout<<“The String is: <<”str; cout<<“\n Strings are not equal”;
} getch();
int operator==(string x) //Comparing String function defined }
{
int a=strcmp(str,x.str);
if (a==0)
return 1;
else
return 0;
}
};
RULES FOR OVERLOADING
OPERATORs :-
1) Only the operators already predefined in the C++ compiler can be overloaded.
2) Overloading cannot change operator's templates. for eg: the increment operator ++ is used only as
unary operator, it cannot be used as binary operator.
3) Overloading an operator should not change its basic meaning. for eg: the ++ operator cannot be
overloaded to subtract two objects.
5) Binary operators overloaded through a member function take one explicit argument and those
overloaded through a friend function [global function] take two explicit arguments.
8) All overloaded operators except assignment (operator=) are inherited by derived classes.
9) If an operator can be used as either a unary or a binary operator (&, *, +, and -), you can
overload each of them separately.
10) Assignment (=), subscript ([]), function call (“()”), and member selection (->) operators must
be defined as member functions when overloaded, not friend functions.
11) Binary arithmetic operators such as +,-,* and / must explicitly return a value.
Function overloading
C++ allows you to specify more than one definition for a function name in the
same scope, which is called function overloading.
An overloaded declaration is a declaration that is declared with the same name as
a previously declared declaration in the same scope, except that both declarations
have different arguments and obviously different definition (implementation).
When you call an overloaded function, the compiler determines the most
appropriate definition to use, by comparing the argument types you have used to
call the function with the parameter types specified in the definitions.
This process of selecting the most appropriate overloaded function is called
overload resolution.
You cannot overload function declarations that differ only by return type.
Write a C++ program to explain the concept of Overloading of
functions.
#include <iostream.h>
# include <conio.h> void main()
class printData { {
public: printData pd;
void print(int i) { pd.print(5); // Call print to print integer
cout << "Printing int: " << i << endl; pd.print(500.263); // Call print to print float
} pd.print("C"); // Call print to print character
void print(double f) { pd.add(12,45);
cout << "Printing Decimal: " << f << endl; pd.add(2,7,9);
} pd.add(2.45,6.74);
void print(char c) { getch();
cout << "Printing character: " << c << endl; }
}
void add(int a,int b) {
cout<<“Addition of two integers:”<<a+b;
}
void add(int a,int b,int c) {
cout<<“Addition of three integers:”<<a+b+c;
}
void add(double a,double b){
cout<<“Addition of two decimals:”<<a+b;
}
};
Inheritance in C++
Inheritance in C++ (contd.)
Inheritance in C++ (contd.)
• Re-usability is yet another feature of OOP's & C++ strongly supports the
concept of reusability.
• Once a class has been written and tested, it can be adopted by another
programmers …that is.. the C++ classes can be used again in several ways.
• This is basically created by defining the new classes, reusing the properties
of existing ones & this mechanism of deriving a new class from an old one is
called 'INHERITANCE'.
• The old class is called 'BASE' class and the new one is called 'DERIVED‘ class.
• The term reusability means reuse of properties of base class in the derived
class.
Inheritance in C++ (Example)
• Consider the vehicle hierarchy:
VEHICLE
AUTOMOBILE BICYCLE
LANDBASED
LANDBASED myLandBased
Vehicle
Example:
Automobile MotorBoat
AutoBoat
Advantages of inheritance
When a class inherits from another class, there
are three benefits:
(1) We can reuse the methods and data of the existing class
(2) We can extend the existing class by adding new data and new
methods
(3) We can modify the existing class by overloading its methods
with your own implementations
Defining a Class Hierarchy
• Syntax:
class DerivedClassName : access-level BaseClassName
where
• access-level specifies the type of derivation
• private by default, or
• public
• Any class can serve as a base class
• Thus a derived class can also be a base class for some new
class defined….
25
Types of Inheritances in C++
Single Level Inheritance
Single Inheritance
The class stdmarks or instance object s1 s2 has a single parent student
Write a C++ program to explain the functionality of
Single level Inheritance [using student database]
class stdmarks : public student
#include<iostream.h> {
#include<conio.h> public:
class student int m1,m2,m3,tot;
{ float per;
public: void getmarks() void main()
int rno; { {
char name[25]; getdata(); stdmarks s1,s2;
void getdata() cout<<"Enter Marks out of 100 in all 3 subjects :- \t"; clrscr();
{ cin>>m1>>m2>>m3; s1.getmarks();
cout<<"Enter RollNo :- \t"; } s1.display();
cin>>rno; void display() s2.getmarks();
cout<<"Enter Name :- \t"; { s2.display();
cin>>name; tot=m1+m2+m3; getch();
} per=(float)tot/3; }
}; cout<<"Roll No : ” << rno<< “Name: ” <<name<<“ Total Marks: ”<<tot<<“ Percentage: “<<per;
} MAIN PROGRAM
};
DERIVED CLASS
BASE CLASS FIRST LEVEL DERIVED CLASS
SECOND LEVEL
Write a C++ program to explain the functionality of Multilevel
Inheritance [using student database]
void student::read()
{
cout<<"enter Roll no and Name "<<endl;
cin>>rl>>nm; void result::process() void main()
} { {
void student:: display() t= s1+s2+s3; result x;
{ p = t/3.0; clrscr();
cout <<"Roll NO:"<<rl<<endl; if (p>=60) x.read();
cout<<"name : "<<nm<<endl; strcpy(div,"first") x.getmarks();
} else if (p>=50) strcpy(div, "second"); x.process();
void marks ::getmarks() else if (p>=35) strcpy(div,"third"); x.display();
{ else strcpy(div,”FAIL”); x.putmarks();
cout<<"enter three subject marks "<<endl; } x.printresult();
cin>>s1>>s2>>s3; void result::printresult() getch();
} { }
void marks ::putmarks() cout<<"total = "<<t<<endl;
{ cout<<"per = "<<p<<endl;
cout <<"subject 1:"<<s1<<endl; cout<<"div = "<<div<<endl; MAIN PROGRAM
cout<<" subject 2 : "<<s2<<endl; }
cout <<"subject 3:"<<s3<<endl;
}
FUNCTION
DEFINITIONS
Hierarchical Inheritance
It is the inheritance hierarchy wherein multiple subclasses inherit from
one base class.
Write a C++ program to explain the functionality of Hierarchical
Inheritance [Calc. of area of polygons]
#include <iostream.h>
class Polygon class Triangle: public Polygon
{ { void main ()
protected: public: {
int width, height; int area () Rectangle rect;
public: { return width * height / 2; } Triangle trgl;
void set_values (int a, int b) }; rect.set_values (4,5);
{ width=a; height=b;} trgl.set_values (4,5);
}; cout << rect.area() << '\n';
cout << trgl.area() << '\n';
class Rectangle: public Polygon getch();
{ }
public:
BASE CLASS int area ()
{ return width * height; } MAIN
}; PROGRAM
DERIVED
CLASSES
Hybrid Inheritance:
It is the inheritance hierarchy that reflects any legal combination of
other four types of inheritance.
DERIVED CLASS
Write a C++ program to explain the functionality of Hybrid
Inheritance [using student database]
void student::read() void sports:: getgrade()
{ {
cout<<"enter Roll no and Name "<<endl; cout<<“Grade in Sports: ”;
cin>>rl>>nm; cin>>grade; void main()
} } {
void student:: display() void result::process() result x;
{ { clrscr();
cout <<"Roll NO:"<<rl<<endl; t= s1+s2+s3; x.read();
cout<<"name : "<<nm<<endl; p = t/3.0; x.getmarks();
} if (p>=60) x.getgrade();
void marks ::getmarks() strcpy(div,"first") x.process();
{ else if (p>=50) strcpy(div, "second"); x.display();
cout<<"enter three subject marks "<<endl; else if (p>=35) strcpy(div,"third"); x.putmarks();
cin>>s1>>s2>>s3; else strcpy(div,”FAIL”); x.printresult();
} } getch();
void marks ::putmarks() void result::printresult() }
{ {
cout <<"subject 1:"<<s1<<endl; cout<<"total = "<<t<<endl; MAIN PROGRAM
cout<<" subject 2 : "<<s2<<endl; cout<<"per = "<<p<<endl;
cout <<"subject 3:"<<s3<<endl; cout<<“Sports Grade= "<<grade<<endl;
} cout<<"div = "<<div<<endl;
}
FUNCTION
DEFINITIONS
Virtual Base Class
The duplication of the inherited members can be avoided by making
common base class as the Virtual Base Class
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.
Need for Virtual Base Classes:
Consider the situation where we have one class A .This class is A is inherited by
two other classes B and C. Both these class are inherited into another in a new
class D as shown in figure below.
As we can see from the figure that data
members/function of class A are inherited
twice to class D, one through class B and
second through class C.
When any data / function member of
class A is accessed by an object of class D,
ambiguity arises as to which data/function
member would be called? One inherited
through B or the other inherited through C.
This confuses compiler and it displays error.
Resolving this Ambiguity
Syntax 1:
To resolve this ambiguity when class B : virtual public A
class A is inherited in both {
};
class B and class C, it is
declared as virtual base class Syntax 2:
by placing a keyword virtual. class C : public virtual A
{
};
Abstract Class
Sometimes implementation of all function cannot be provided in a base class
because programmer doesn’t know the implementation. Such a class is called
abstract class.
Sometimes, when we have partial set of implementation of methods in a class. For
example, consider a class have four methods. Out of four methods, we have an
implementation of two methods and we need derived class to implement other
two methods. In these kind of situations, abstract class is used.
Eg. Let Shape be a base class. We cannot provide implementation of function
draw() in Shape, but we know every derived class must have implementation of
draw().
Example of Abstract Class class DerivedClass : public BaseClass
#include<iostream.h> {
#include<conio.h> public:
class BaseClass //Abstract class void Display1()
{ {
public: cout<<"\n\tThis is Display1() method of Derived Class";
virtual void Display1()=0; //Pure virtual function or abstract function }
virtual void Display2()=0; //Pure virtual function or abstract function void Display2()
void Display3() {
{ cout<<"\n\tThis is Display2() method of Derived Class";
cout<<"\n\tThis is Display3() method of Base Class"; }
} };
};
void main()
{
DerivedClass D;
D.Display1(); // This will invoke Display1() method of Derived Class
D.Display2(); // This will invoke Display2() method of Derived Class
D.Display3(); // This will invoke Display3() method of Base Class
}
Output :
This is Display1() method of Derived Class
This is Display2() method of Derived Class
This is Display3() method of Base Class
Pure virtual function & Abstract Class
• A virtual function will become pure virtual
function when you append "=0" at the end of
declaration of virtual function.
• A class with at least one pure virtual function is
called abstract class.
• Pure virtual function is also known as abstract
function.
• A pure virtual function (or abstract function) in
C++ is a virtual function for which we don’t have
implementation, we only declare it. A pure
virtual function is declared by assigning 0 in
declaration.
Abstract function & Abstract Class