C++ polymorphism
Created By: chatGPT
Polymorphism is one of the core concepts of object-oriented programming in C++. It allows methods to do different things based on the object it is acting upon, thus enabling a single interface to control access to a group of related classes. There are two types of polymorphism in C++: compile-time and runtime.Compile-time polymorphism is achieved through function overloading and operator overloading. It is resolved during compile time, allowing the same function name to be used for different tasks.
Here's an example of function overloading:
In the above code, the class Print {
public:
void show(int i) {
std::cout << "Integer: " << i << std::endl;
}
void show(double d) {
std::cout << "Double: " << d << std::endl;
}
void show(std::string s) {
std::cout << "String: " << s << std::endl;
}
};
show
method is overloaded to accept various types of arguments (int, double, string). Next, let's discuss runtime polymorphism, which is commonly implemented using inheritance and virtual functions. This type of polymorphism is resolved at runtime.Here's an example of runtime polymorphism using virtual functions:
class Base {
public:
virtual void show() {
std::cout << "Base class" << std::endl;
}
};
class Derived : public Base {
public:
void show() override {
std::cout << "Derived class" << std::endl;
}
};
In this example, the
In conclusion, polymorphism is an essential feature of C++ that enables flexible and reusable code. Using polymorphism wisely can greatly enhance the design of your classes and interfaces.show
method in the Base
class is declared as virtual
, allowing derived classes to override it. When we invoke the show
method using a base class pointer that points to a derived class object, the derived class's implementation will be called, demonstrating runtime polymorphism.int main() {
Base* b = new Derived();
b->show(); // Output: Derived class
delete b;
return 0;
}