Introduction
C++ में Inheritance OOP (Object-Oriented Programming) का एक बहुत महत्वपूर्ण concept है। इसके माध्यम से एक class दूसरी class की properties (data members) और behaviors (member functions) को reuse कर सकती है।
Inheritance का मुख्य उद्देश्य code reuse, extensibility और hierarchical relationship को establish करना है।
जब एक class दूसरी class से features लेती है, तो:
- जिस class से features लिए जाते हैं → Base Class (Parent Class)
- जो class features लेती है → Derived Class (Child Class)
इससे program modular और manageable बनता है।
Definition
Inheritance वह प्रक्रिया है जिसमें एक class दूसरी class के properties और functions को inherit करती है, ताकि code reuse हो सके और नए features आसानी से add किए जा सकें।
Base Classes and Derived Classes
Concept
- Base Class: Parent class जो properties provide करती है
- Derived Class: Child class जो base class से features inherit करती है
Syntax
class Base {
// members
};
class Derived : access_specifier Base {
// additional members
};
Example
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};
class Dog : public Animal {
public:
void bark() {
cout << "Barking..." << endl;
}
};
int main() {
Dog d;
d.eat(); // inherited function
d.bark(); // own function
return 0;
}
Output
Eating...
Barking...
Explanation
Animal→ Base ClassDog→ Derived ClassDogclass नेeat()function inherit किया- साथ ही अपना खुद का function
bark()भी add किया
Types of Inheritance (Brief)
- Single Inheritance
- Multiple Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance
Important Points
- Derived class base class के public और protected members को access कर सकती है
- Private members directly access नहीं होते
- Code duplication कम होता है
- Real-world relationships को model करने में मदद मिलती है
निष्कर्ष
Inheritance C++ का एक powerful concept है जो code reuse और relationship building को आसान बनाता है। यह बड़े programs को modular और scalable बनाने में महत्वपूर्ण भूमिका निभाता है।