GP-CPP-OOPS-Compile Time Polymorphism
GP-CPP-OOPS-Compile Time Polymorphism
Overview
Compile time polymorphism is also known as static polymorphism. This type of
a) Function overloading: When there are multiple functions in a class with the same
name but different parameters, these functions are overloaded. The main advantage of
arguments.
In this example, we have created two functions, the first add() performs the addition of
the two numbers, and the second add() performs the addition of the three numbers.
#include <iostream>
using namespace std;
int main() {
1
return 0;
}
Output:
30
60
In this example, we have created two add() functions with different data types. The first
add() takes two integer arguments and the second add() takes two double arguments.
#include <iostream>
int main(void) {
Output:
30
30.9
automatically assigned by the compiler if the function’s caller doesn’t provide a value for
2
the argument with a default value. However, if arguments are passed while calling the
arguments.
#include<iostream>
int main() {
cout << add(10, 20) << endl;
cout << add(10, 20, 30) << endl;
cout << add(10, 20, 30, 40) << endl;
return 0;
}
Output:
30
60
100
example, we can make the operator (‘+’) for the string class to concatenate two strings.
We know that this is the addition operator whose task is to add two operands. A single
operator, ‘+,’ when placed between integer operands, adds them and concatenates
3
● Operators = and & are already overloaded in C++, so we can avoid overloading
them.
#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0) {
real = r;
imag = i;
}
4
// This is automatically called when '+' is used with
// between two Complex objects
Complex operator + (Complex
const & b) {
Complex a;
a.real = real + b.real;
a.imag = imag + b.imag;
return a;
}
void print() {
cout << real << " + i" << imag << endl;
}
};
int main() {
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
}
Output:
12 + i9