Polymorphism in C++ is the ability of objects of different classes to be treated as if they were objects of a common base class. There are two types of polymorphism in C++:
Here’s an example of function overloading:
#include
using namespace std;
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
float add(float a, float b) {
return a + b;
}
};
int main() {
Calculator calc;
cout << calc.add(2, 3) << endl; // calls int add(int, int)
cout << calc.add(2.5f, 3.5f) << endl; // calls float add(float, float)
return 0;
}
Here’s an example of runtime polymorphism using virtual functions:
#include
using namespace std;
class Shape {
public:
virtual void draw() {
cout << "Drawing a shape." << endl;
}
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a circle." << endl;
}
};
class Rectangle : public Shape {
public:
void draw() override {
cout << "Drawing a rectangle." << endl;
}
};
int main() {
Shape* s1 = new Circle();
Shape* s2 = new Rectangle();
s1->draw(); // calls Circle's draw()
s2->draw(); // calls Rectangle's draw()
return 0;
}
Note that the virtual keyword is used in the base class method declaration to indicate that the method is virtual, and it is overridden in the derived classes using the override keyword.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.