0% found this document useful (0 votes)
39 views13 pages

Unit-5 (Polymorphism)

The document discusses polymorphism in object-oriented programming, detailing compile-time and run-time polymorphism, along with examples of function and operator overloading. It also covers method overriding, pure virtual functions, and exception handling in C++. Additionally, the document explains file handling in C++ using the fstream library for reading and writing files.

Uploaded by

furryk24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views13 pages

Unit-5 (Polymorphism)

The document discusses polymorphism in object-oriented programming, detailing compile-time and run-time polymorphism, along with examples of function and operator overloading. It also covers method overriding, pure virtual functions, and exception handling in C++. Additionally, the document explains file handling in C++ using the fstream library for reading and writing files.

Uploaded by

furryk24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

UNIT-5

Polymorphism
The term "Polymorphism" is the combination of "poly" + "morphs"
which means many forms. It is a greek word. In object-oriented
programming, we use 3 main concepts: inheritance, encapsulation, and
polymorphism.

o Compile time polymorphism: The overloaded functions are invoked by


matching the type and number of arguments. This information is available at
the compile time and, therefore, compiler selects the appropriate function at the
compile time. It is achieved by function overloading and operator overloading
which is also known as static binding or early binding. Now, let's consider the
case where function name and prototype is same.

class A // base class declaration.


{
int a;
public:
void display()
{
cout<< "Class A ";
}
};
class B : public A // derived class declaration.
{
int b;
public:
void display()
{
cout<<"Class B";
}
};
the prototype of display() function is the same in both the base and derived class. Therefore, the
static binding cannot be applied. It would be great if the appropriate function is selected at the run
time. This is known as run time polymorphism.
o Run time polymorphism: Run time polymorphism is achieved when the object's
method is invoked at the run time instead of compile time. It is achieved by
method overriding which is also known as dynamic binding or late binding.

Types of overloading in C++ are:


Function overloading/Method overloading

Operator overloading

Method Overloading
Function Overloading is defined as the process of
having two or more function with the same name,
but different in parameters is known as function
overloading in C++. In function overloading, the
function is redefined by using either different types
of arguments or a different number of arguments. It
is only through these differences compiler can
differentiate between the functions.

//program of function overloading when number of arguments vary.

#include <iostream>
using namespace std;
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
Output:
30
55

welcome bridget in becse enginnering


C++

Operator Overloading

Syntax of Operator Overloading

return_type class_name : : operator op(argument_list)


{
// body of the function.
}

Where the return type is the type of value returned by the function.

class_name is the name of the class.

operator op is an operator function where op is the operator being overloaded,


and the operator is the keyword.

#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++() {
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}
The Count is: 10

Method Overriding
If derived class defines same function as defined in
its base class, it is known as function overriding in
C++. It is used to achieve runtime polymorphism. It
enables you to provide specific implementation of
the function which is already provided by its base
class.

Function/Method Overriding Example


In this example, we are overriding the eat() function.

#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
};
int main(void) {
Dog d = Dog();
d.eat();
return 0;
}
Output:

Eating bread...

Runtime Polymorphism Example


Let's see a simple example of run time polymorphism
in C++.

// an example without the virtual keyword.

#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{ cout<<"Eating bread...";
}
};
int main() {
Dog d = Dog();
d.eat();
return 0;
}
Output:

Eating bread...

Run time Polymorphism Example: By


using two derived class (an example with virtual
keyword.)

Let's see another example of run time polymorphism in C++


where we are having two derived classes.

// an example with virtual keyword.

#include <iostream>
using namespace std;
class Shape { // base class
public:
virtual void draw(){ // virtual function
cout<<"drawing..."<<endl;
}
};
class Rectangle: public Shape // inheriting Shape class.
{
public:
void draw()
{
cout<<"drawing rectangle..."<<endl;
}
};
class Circle: public Shape // inheriting Shape class.
{
public:
void draw()
{
cout<<"drawing circle..."<<endl;
}
};
int main() {
Shape *s; // base class pointer.
Shape sh; // base class object.
Rectangle rec;
Circle cir;
s=&sh;
s->draw();
s=&rec;
s->draw();
s=&cir;
s->draw();
}
drawing...
drawing rectangle...
drawing circle...

Pure Virtual Function


o A virtual function is not used for performing any task. It only serves as a placeholder.

o When the function has no definition, such function is known as "do-nothing" function.

o The "do-nothing" function is known as a pure virtual function. A pure virtual function is a
function declared in the base class that has no definition relative to the base class.

Pure virtual function can be defined as:

virtual void display() = 0;

#include <iostream>
using namespace std;
class Base
{
public:
virtual void show() = 0;
};
class Derived : public Base
{
public:
void show()
{
cout << "Derived class is derived from the base class." << std::endl;
}
};
int main()
{
Base *bptr;
//Base b;
Derived d;
bptr = &d;
bptr->show();
return 0;
}

Derived class is derived from the base class.

Exception Handling
Exception Handling in C++ is a process to handle runtime errors. We
perform exception handling so the normal flow of the application can be
maintained even after runtime errors.
In C++, exception is an event or object which is thrown at runtime. All
exceptions are derived from std::exception class. It is a runtime error
which can be handled. If we don't handle the exception, it prints
exception message and terminates the program.

Exception Handling Keywords


In C++, we use 3 keywords to perform exception handling:

Try

Catch

throw

The try statement allows you to define a block of code to be tested for errors while it is
being executed.

The throw keyword throws an exception when a problem is detected, which lets us create
a custom error.

The catch statement allows you to define a block of code to be executed, if an error occurs
in the try block.

try

{
// Block of code to try
throw exception; // Throw an exception when a problem
arise
}
catch () {
// Block of code to handle errors
}

o try

o catch, and

o throw

#include <iostream>
using namespace std;
float division(int x, int y)
{
if( y == 0 )
{
throw "Attempted to divide by zero!";
}
return (x/y);
}
int main () {
int i = 25;
int j = 0;
float k = 0;
try {
k = division(i, j);
cout << k << endl;
}
catch (const char* e) {
cerr << e << endl;
}
return 0;
}
Output:
Attempted to divide by zero!

#include <iostream>
using namespace std;

int main() {
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum;
}
return 0;
}
Multiple try and catch statements

#include <iostream>

using namespace std;

int main()

try {

try{

throw 20;

catch (int n) {

cout<< "Handle Partially ";

throw;//Re-throwing an exception

catch (int n) {

cout<< "Handle remaining ";

return 0;

Files and Streams


In C++ programming we are using the iostream standard library, it
provides cin and cout methods for reading from input and writing to
output respectively.File is a collection of records or collection od data.

To read and write from a file we are using the standard C++ library
called fstream. Let us see the data types define in fstream library is:

Data Type Description

fstream It is used to create files, write information to files, and read information from files.

ifstream It is used to read information from files.

ofstream It is used to create files and write information to the files.

Writing data to a file

#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream filestream("a.txt");
if (filestream.is_open())
{
filestream << "Welcome \n";
filestream << "C++ \n";
filestream.close();
}
else cout <<"File opening is fail.";
return 0;
}

reading from a file


#include <iostream>
#include <fstream>
using namespace std;
int main () {
string srg;
ifstream filestream("testout.txt");
if (filestream.is_open())
{
while ( getline (filestream,srg) )
{
cout << srg <<endl;
}
filestream.close();
}
else {
cout << "File opening is fail."<<endl;
}
return 0;
}

You might also like