Q7. Demonstrate Use of Virtual Class
Question:
Write program to demonstrate use of virtual class.
My Approach
C++ me virtual class ka concept mainly multiple inheritance ambiguity (diamond problem) ko solve karne ke liye use hota hai.
- Agar ek base class ko do intermediate classes inherit karein aur fir ek derived class un dono se inherit kare, to base class ke members duplicate ho jate hain.
- Is problem ko solve karne ke liye base class ko virtual base class banate hain.
Program Code
File Name: virtual_class_demo.cpp
#include <iostream>
using namespace std;
// Base class
class Person {
public:
string name;
int age;
Person(string n, int a) : name(n), age(a) {}
void displayPerson() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
// Derived virtually
class Student : virtual public Person {
public:
int rollNo;
Student(string n, int a, int r) : Person(n, a), rollNo(r) {}
void displayStudent() {
cout << "Roll No: " << rollNo << endl;
}
};
// Derived virtually
class Employee : virtual public Person {
public:
string company;
Employee(string n, int a, string c) : Person(n, a), company(c) {}
void displayEmployee() {
cout << "Company: " << company << endl;
}
};
// Derived from both Student and Employee
class WorkingStudent : public Student, public Employee {
public:
WorkingStudent(string n, int a, int r, string c)
: Person(n, a), Student(n, a, r), Employee(n, a, c) {}
void display() {
displayPerson();
displayStudent();
displayEmployee();
}
};
// ================= Main Function =================
int main() {
WorkingStudent ws("Intesab Ansari", 24, 101, "Taqdis Computers");
cout << "=== Virtual Class Demo ===" << endl;
ws.display();
return 0;
}Sample Output
=== Virtual Class Demo ===
Name: Intesab Ansari, Age: 24
Roll No: 101
Company: Taqdis ComputersExplanation
- Agar
Personko virtual base class na banaya jata, toWorkingStudentmePersonka duplicate copy ban jata (ekStudentse aur ekEmployeese). virtualkeyword ensure karta hai kiPersonka sirf ek hi copy banegi, aur ambiguity solve ho jayegi.
Real-Life Relevance
- Example: Tum ek Student bhi ho aur ek Employee bhi (internship ke time par).
- Dono roles ke liye tum ek hi Person ho, isliye
Personka duplicate copy banana galat hota. - Virtual class ensure karti hai ki tumhari identity (name, age) ek hi jagah se manage ho.
Conclusion
Virtual classes ka use diamond problem avoid karne ke liye hota hai.
Ye ek important OOPs feature hai jo multiple inheritance me consistency maintain karta hai.
Submitted by:
Intesab Ansari
MCA Student, NMU University
Portfolio: intesab.live
Last updated on