Polymorphism means more than one function with same name, with different working.
Polymorphism can be static or dynamic.
In static polymorphism memory will be allocated at compile-time.
In dynamic polymorphism memory will be allocated at run-time.
Both function overloading and operator overloading are an examples of static polymorphism. Virtual function is an example of dynamic polymorphism.
Static polymorphism is also known as early binding and compile-time polymorphism.
Dynamic polymorphism is also known as late binding and run-time polymorphism.
Virtual function is a member function in base class, that you redefined in derived class.
Virtual function is used in situation, when we need to invoke derived class function using base class pointer. We must declare base class function as virtual using virtual keyword preceding its normal declaration.
The base class object must be of pointer type so that we can dynamically replace the address of base class function with derived class function. This is how we can achieve "Runtime Polymorphism".
Example of virtual function
#include<iostream>
using namespace std;
class BaseClass
{
public:
virtual void Display()
{
cout<<"\n This is Display() method of Base Class";
}
};
class DerivedClass : public BaseClass
{
public:
void Display()
{
cout<<"\n This is Display() method of Derived Class";
}
};
int main()
{
BaseClass *bp; //Creating Base Class Pointer DerivedClass D;
bp=&D;
bp->Display(); //This will invoke Display() method of Derived Class BaseClass B;
bp=&B;
bp->Display(); //This will invoke Display() method of Base Class
}
Output:
This is Display() method of Derived Class
This is Display() method of Base Class
Purpose of C++ Templates:\
Avoids writing the same function or class for different data types.
Enhances code reusability and flexibility.
When to Use:
When a function or class needs to work with different data types (e.g., adding integers, floats, doubles).
How it Works:
Templates allow functions or classes to work with various data types without duplicating code.
Types of Templates in C++:
Function Template: For creating functions that can operate on different data types.
Class Template: For defining classes that can work with various data types.
Benefit: Makes programs simpler, more efficient, and easier to maintain.
Definition:
A generic function that performs the same task on different data types.
Purpose:
Allows a single function to operate on different data types using the same code.
How it Works:
Unlike regular functions that require separate definitions for each data type, a function template handles all types with one definition.
Comparison with Function Overloading:
Function overloading requires writing separate functions for each data type.
Function templates eliminate redundancy by creating a generic function for similar operations.
Benefit:
Less code, better maintainability, and improved efficiency.
syntax:
A function template starts with keyword template followed by template parameter/s inside <> which is followed by function declaration
template<class T>
T some_function( T argument)
{
 ----
 ----
}
In the above code, T is a template argument that accepts different data types (int, float), and class is a keyword.
You can also use keyword typename instead of class in the above example.
template<class T>
template<typename T>
C++ Program to Add two numbers using function template
#include<iostream>
using namespace std;
template <class T>
T sum(T a, T b)
{
return a+b;
}
int main()
{
cout<<"Integer sum = "<<sum(2,10)<<endl;
cout<<"Float sum = "<<sum(1.5,2.5);
}
Output
Integer sum = 12
Float sum = 4
Write a Program to define function template with multiple arguments.
#include<iostream>
using namespace std;
template <class t1, class t2>
void sum(t1 a,t2 b)
{
cout<<"sum = "<<a+b<<endl;
}
int main()
{
sum(1,2.5);
sum(2.5,3);
return 0;
}
Output
sum = 3.5
sum = 5.5
Purpose:
To create generic classes that work with different data types using the same code.
How it Works:
A single class template can handle multiple data types without creating separate classes for each.
Comparison with Regular Classes:
Regular classes require defining separate classes or members for each data type.
Class templates eliminate redundancy and simplify maintenance.
Benefit:
Improved code reusability, consistency, and easier maintenance.
Use Case:
When you need a class implementation that is the same for all classes, differing only in data types.
Syntax
In order to declare a class syntax this syntax is followed
template<class T>
class class_name
{
  //class data members and functions
}
Syntax for defining/create an object of a template class is:
classname <type> objectname(argument list)
For example:
className<int> classObject;
className<float> classObject;
className<string> classObject;
C++ Program to Add two numbers using class template
#include<iostream>
using namespace std;
template <class T>
class Test
{
T a,b;
public:
void getdetails()
{
cout<<"enter values"<<endl;
cin>>a>>b;
}
T sum()
{
cout<<"sum = "<<a+b<<endl;
}
};
int main()
{
Test<int> obj1;
obj1.getdetails();
obj1.sum();
Test<float> obj2;
obj2.getdetails();
obj2.sum();
}
Output:
enter values
10 20
sum = 30
enter values
1.2 3.6
sum = 4.8
An error is a mistake done by the programmer.
The errors are broadly divided into two types Compile time errors and Run time errors.
The errors which occur at the time of compiling the program are called as compile time errors.
The compile time errors can be easily rectified by the programmer.
The compile time error may occur due to logical (or) syntactic errors in the program.
The errors which occur at the time of running the program are called as run time errors.
The run time errors may abnormally terminate the program. These may hang the system too.
The run time errors need to be handled in a proper way. The handling of these run time errors is called as Exception Handling.
An exception is a situation, which occurred by the runtime error. In other words, an exception is a runtime error. An exception may result in loss of data or an abnormal execution of program.
Exception includes condition such as
-> division by zero,
-> accessing an array outside its bound, (i.e out of range index)
-> running out of memory, etc
Exception handling mechanism consists of following parts
Find the problem (Hit the exception)
Inform about its occurrence (Throw the exception)
Receive error information (Catch the exception)
Take proper action (Handle the exception)
Exception handling is a mechanism that allows you to take appropriate action to avoid runtime errors.
C++ provides three keywords to support exception handling.
Try: The try block contain statements which may generate exceptions.
Throw: When an exception occur in try block, it is thrown to the catch block using throw keyword.
Catch: The catch block defines the action to be taken, when an exception occur.
The general form of try-catch block in c++.
Example of simple try-throw-catch
#include<iostream>
using namespace std;
int main()
{
int a,b;
cout<<"enter a and b"<<endl;
cin>>a>>b;
try
{
if(b==0)
throw b;Â
else
cout<<"division is "<<a/b;
}
catch(int n)
{
cout<<"divison is not possible";
}
return 0;
}
This function is used to transfer the error from try block to catch block. This function plays major role to save program from crashing.
Exception thrown using the throw statement in one of the following forms.
throw (exception);
throw exception;
throw;
The catch block contain the code to handle exception. The catch block is similar to function definition.
catch(data-type arg)
{
- - - - - - - - - -
- - - - - - - - - -
- - - - - - - - - -
};
Data-type specifies the type of exception that catch block will handle, Catch block will receive value, send by throw keyword in try block.