Unit IV
Unit IV
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.
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.
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.
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;
}
The function to be invoked is known at the The function to be invoked is known at the
compile time. 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.
#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:
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.
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:
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.
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;
}
};
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.
• 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.
The three objects, that is, fstream, ofstream, and ifstream, have the open() function defined in
them. The function takes this syntax:
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;
}
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;
}
#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;
}