0% found this document useful (0 votes)
13 views12 pages

Unit IV

Uploaded by

manishhadiabad70
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)
13 views12 pages

Unit IV

Uploaded by

manishhadiabad70
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/ 12

Polymorphism

The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A real-
life example of polymorphism, a person at the same time can have different characteristics.
Like a man at the same time is a father, a husband, an employee so the same person possess
different behavior in different situations. This is called polymorphism. Polymorphism is
considered as one of the important features of Object Oriented Programming.

There are two types of polymorphism in C++:

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.

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";
}
};

In the above case, 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.

Function 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.

The advantage of Function overloading is that it increases the readability of the program
because you don't need to use different names for the same action.

C++ Function Overloading Example

Let's see the simple example of function overloading where we are changing number of
arguments of add() method.

#include<iostream.h>
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()
{
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}

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.

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.

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

Differences between compile time and run time polymorphism.

Compile time polymorphism/Early Run time polymorphism/Late


Binding/Static Binding Binding/Dynamic Binding

The function to be invoked is known at the The function to be invoked is known at the
compile time. run time.

It is also known as overloading, early binding It is also known as overriding, Dynamic


and static binding. binding and late binding.

Overloading is a compile time polymorphism Overriding is a run time polymorphism


where more than one method is having the same where more than one method is having the
name but with the different number of same name, number of parameters and the
parameters or the type of the parameters. type of the parameters.

It is achieved by function overloading and It is achieved by virtual functions and


operator overloading. pointers.

It provides fast execution as it is known at the It provides slow execution as it is known at


compile time. the run time.

It is less flexible as mainly all the things execute It is more flexible as all the things execute
at the compile time. at the run time.

Virtual function

o A C++ virtual function is a member function in the base class that you redefine in a
derived class. It is declared using the virtual keyword.
o It is used to tell the compiler to perform dynamic linkage or late binding on the
function.
o There is a necessity to use the single pointer to refer to all the objects of the different
classes. So, we create the pointer to the base class that refers to all the derived objects.
But, when base class pointer contains the address of the derived class object, always
executes the base class function. This issue can only be resolved by using the 'virtual'
function.
o A 'virtual' is a keyword preceding the normal declaration of a function.

Rules of Virtual Function

o Virtual functions must be members of some class.


o Virtual functions cannot be static members.
o They are accessed through object pointers.
o They can be a friend of another class.
o A virtual function must be defined in the base class, even though it is not used.
o We cannot have a virtual constructor, but we can have a virtual destructor
o Consider the situation when we don't use the virtual keyword.

#include<iostream.h>
class A
{
int x=5;
public:
void display()
{
cout << "Value of x is : " << x<<endl;
}
};
class B: public A
{
int y = 10;
public:
void display()
{
cout << "Value of y is : " <<y<<endl;
}
};
int main()
{
A *a;
B b;
a = &b;
a->display(); //to call member function from pointer arrow operator is used.
return 0;
}

Output:
Value of x is: 5

In the above example, * a is the base class pointer. The pointer can only access the
base class members but not the members of the derived class. Therefore, there is a
need for virtual function which allows the base pointer to access the members of the
derived class.
Virtual function Example

Let's see the simple example of C++ virtual function used to invoked the derived class in a
program.

#include <iostream.h>
Class A
{
public:
virtual void display()
{
cout << "Base class is invoked"<<endl;
}
};
class B:public A
{
public:
void display()
{
cout << "Derived Class is invoked"<<endl;
}
};
int main()
{
A* a; //pointer of base class
B b; //object of derived class
a = &b;
a->display(); //Late Binding occurs
}

Output:

Derived Class is invoked

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.
o A class containing the pure virtual function cannot be used to declare the objects of its
own, such classes are known as abstract base classes.
o Pure virtual function always initializes with 0 only.
o Do not define the VIRTUAL keyword while redefining the virtual function.

Pure virtual function can be defined as:

virtual void display() = 0;

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

Output:

Derived class is derived from the base class.


In the above example, the base class contains the pure virtual function. Therefore, the base
class is an abstract base class. We cannot create the object of the base class.

Abstract class

An abstract class in C++ is a class that has at least one pure virtual function (i.e., a function
that has no definition). The classes inheriting the abstract class must provide a definition for
the pure virtual function; otherwise, the subclass would become an abstract class itself.

Features of Abstract Class

1) A class is abstract if it has at least one pure virtual function.


2) We can have pointers and references of abstract class type.
3) If we do not override the pure virtual function in derived class, then derived
class also becomes abstract class.
4) An abstract class can have constructors.
5) This class is not used for defining object, it is used just for inheritance.

Example:

#include<iostream.h>
class Shape
{
protected:
int shape_width;
int shape_height;

public:
virtual int perimeter() = 0;
void width(int w)
{
shape_width = w;
}
void height(int h)
{
shape_height = h;
}
};

class Rectangle: public Shape


{
public:
int perimeter()
{
return (2 * (shape_width + shape_height));
}
};
int main()
{
Rectangle R;
R.width(10);
R.height(5);
cout << "Perimeter of Rectangle: " << R.perimeter() << endl;
return 0;
}

File Handling in C++


Files store data permanently in a storage device. With file handling, the output from a
program can be stored in a file. Various operations can be performed on the data while in the
file.

A stream is an abstraction of a device where input/output operations are performed. You can
represent a stream as either a destination or a source of characters of indefinite length. This
will be determined by their usage. C++ provides you with a library that comes with methods
for file handling.

The fstream Library


The fstream library provides C++ programmers with three classes for working with files.
These classes include:

• ofstream– This class represents an output stream. It’s used for creating files and
writing information to files.
• ifstream– This class represents an input stream. It’s used for reading information from
data files.
• fstream– This class generally represents a file stream. It comes with ofstream/ifstream
capabilities. This means it’s capable of creating files, writing to files, reading from
data files.

To use the above classes of the fstream library, you must include it in your program as a
header file. You must also include the iostream header file.

How to Open Files


Before performing any operation on a file, you must first open it. If you need to write to the
file, open it using fstream or ofstream objects. If you only need to read from the file, open it
using the ifstream object.

The three objects, that is, fstream, ofstream, and ifstream, have the open() function defined in
them. The function takes this syntax:

open (file_name, mode);


• The file_name parameter denotes the name of the file to open.
• The mode parameter is optional. It can take any of the following values:

Value Description
ios:: app The Append mode. The output sent to the file is appended to it.
ios::ate It opens the file for the output then moves the read and write control to file’s end.
ios::in It opens the file for a read.
ios::out It opens the file for a write.
ios::trunc If a file exists, the file elements should be truncated prior to its opening.

It is possible to use two modes at the same time. You combine them using the | (OR)
operator.

#include <iostream.h>
#include <fstream.h>
int main()
{
fstream my_file;
my_file.open("my_file", ios::out);
if (!my_file)
{
cout << "File not created!";
}
else
{
cout << "File created successfully!";
my_file.close();
}
return 0;
}

How to Close Files


Once a C++ program terminates, it automatically

• flushes the streams


• releases the allocated memory
• closes opened files.

The fstream, ofstream, and ifstream objects have the close() function for closing files. The
function takes this syntax:

void close();
How to Write to Files
You can write to file right from your C++ program. You use stream insertion operator (<<)
for this. The text to be written to the file should be enclosed within double-quotes.

#include <iostream.h>
#include <fstream.h>
int main()
{
fstream my_file;
my_file.open("my_file.txt", ios::out);
if (!my_file)
{
cout << "File not created!";
}
else
{
cout << "File created successfully!";
my_file << "Hello";
my_file.close();
}
return 0;
}

How to Read from Files


You can read information from files into your C++ program. This is possible using stream
extraction operator (>>). You use the operator in the same way you use it to read user input
from the keyboard. However, instead of using the cin object, you use the ifstream/fstream
object.

#include <iostream.h>
#include <fstream.h>
int main()
{
fstream my_file;
my_file.open("my_file.txt", ios::in);
if (!my_file)
{
cout << "No such file";
}
else {
char ch;

while (1)
{
my_file >> ch;
if (my_file.eof())

break;
cout << ch;
}

}
my_file.close();
return 0;
}

You might also like