Junior
What is polymorphism in the context of C/C++ programming languages?
sobes.tech AI
Answer from AI
Polymorphism is the property of objects to have many forms or represent multiple types in an inheritance hierarchy. It allows working with objects of different classes through a common interface of the base class.
In C++, polymorphism is implemented in two main ways:
-
Compile-time polymorphism (static, ad-hoc polymorphism):
- Implemented using function overloading and operator overloading.
- The specific function or operator implementation is chosen at compile time.
// Example of function overloading void print(int a) { /* ... */ } void print(double b) { /* ... */ } -
Runtime polymorphism (dynamic, subtype polymorphism):
- Implemented using virtual functions and pointers/references to the base class.
- The specific function implementation is chosen at runtime.
- Requires at least one virtual function in the base class.
- Uses a virtual table (vtable).
// Example of dynamic polymorphism class Base { public: virtual void show() { /* Base class implementation */ } }; class Derived : public Base { public: void show() override { /* Overridden implementation */ } }; // Usage Base* ptr = new Derived(); ptr->show(); // Calls Derived::show()
Polymorphism allows writing more flexible and extensible code, as new classes can be added without modifying existing code that works with the base class.