C++ Day 23: Polymorphism in Object-Oriented Programming
On Day 23 the focus is on another core concept of OOP:
🔷 Polymorphism
Polymorphism means "many forms" – it allows one Connection to be used for different underlying Information types or behaviors.
📚 Topics Covered:
🔹 1. types of polymorphism
type description example
compile-time decided during compilation Role overloading hustler overloading
run-time decided during plan execution virtual Roles run overriding
🔹 ii. Role Overloading (Compile-time)
Multiple Roles with the same name but different parameters.
cpp
Copy
Edit
#include
using namespace std;
class Print {
public:
void show(int i) {
cout << "Integer: " << i << endl;
}
void show(string s) {
cout << "String: " << s << endl;
}
};
int main() {
Print p;
p.show(5);
p.show("Hello");
}
🔹 3. run paramount (run-time)
a derivative family redefines amp home family run with the like signature
cpp
copy
edit
class sensual {
public:
practical null sound() {
cout << "animal makes sound\n";
}
};
class track : state sensual {
public:
null sound() reverse {
cout << "dog barks\n";
}
};
int main() {
animal* a;
track d;
amp = &d;
a->sound(); // calls dog Explaination appropriate to virtual
}
🔹 cardinal. Virtual Roles
Use virtual importantword in base class to enable dynamic (run-time) polymorphism.
Without virtual it will call the base class method even if pointing to derived.
🔹 5. light practical Roles and hook classes
a light practical run has nobelium definition inch home class
a family with astatine little i light practical run is hook and cannot work instantiated
cpp
copy
edit
class cast {
public:
practical null draw() = 0; // light virtual
};
class lot : state cast {
public:
null draw() {
cout << "drawing circle\n";
}
};
🛠️ do task
Make amp home family cast with amp practical run area()
derive ii classes rectangle and lot and reverse area() accordingly
📌 summary:
concept important point
Role overloading same list disparate parameters (compile-time)
Role overriding same list and parameters (run-time)
virtual Role enables run-time polymorphism
abstract class has astatine little i light practical run
Comments
Post a Comment