If we do not use the virtual keyword, function overriding
still happens, but it does not achieve runtime polymorphism. Instead, early
binding (compile-time binding) occurs.
Function overriding allows a derived class to redefine a
function from its base class. Using the virtual keyword in the base class
enables runtime polymorphism (dynamic binding).
Example
#include <iostream>
using namespace std;
// Base class
class Student {
public:
string name;
int rollNo;
void getDetails() {
cout << "Enter Student Name: ";
cin >> name;
cout << "Enter Roll Number: ";
cin >> rollNo;
}
virtual void display() { // Virtual function
cout << "Student Name: " << name << ", Roll No: " << rollNo << endl;
}
};
// Derived class
class Result : public Student {
public:
float marks;
void getDetails() {
Student::getDetails(); // Call base class function
cout << "Enter Marks: ";
cin >> marks;
}
void display() { // Overriding function
cout << "Student Name: " << name << ", Roll No: " << rollNo << ", Marks: " << marks << endl;
}
};
int main() {
Student* s; // Base class pointer
Result r; // Derived class object
r.getDetails(); // Get student and result details
s = &r;
s->display(); // Calls Result class's display() (Runtime Polymorphism)
return 0;
}
No comments:
Post a Comment