Introduction
Inheritance Object Oriented Programming का एक महत्वपूर्ण concept है, जिसके माध्यम से एक class (derived class) दूसरी class (base class) के properties और functions को प्राप्त करती है। इससे code reuse और hierarchy बनाना आसान हो जाता है।
C++ में inheritance के साथ access control भी जुड़ा होता है, जो यह निर्धारित करता है कि base class के members derived class में किस रूप में उपलब्ध होंगे। इसी आधार पर inheritance के तीन प्रकार होते हैं — Public, Private और Protected Inheritance।
Definition
Inheritance के साथ उपयोग किए जाने वाले access specifiers (public, private, protected) यह निर्धारित करते हैं कि base class के members derived class में किस access level पर उपलब्ध होंगे।
Syntax
class DerivedClass : accessSpecifier BaseClass {
// body
};
1. Public Inheritance
Description
जब base class को public रूप में inherit किया जाता है, तो:
- base class के public members → public रहते हैं
- protected members → protected रहते हैं
- private members → directly accessible नहीं होते
Example
#include <iostream>
using namespace std;class Base {
public:
int x;
};
class Derived : public Base {
public:
void show() {
cout << x;
}
};
int main() {
Derived d1;
d1.x = 10;
d1.show();
return 0;
}
Output:
10
2. Private Inheritance
Description
जब base class को private रूप में inherit किया जाता है, तो:
- base class के public और protected members → private बन जाते हैं
- private members → accessible नहीं होते
Example
#include <iostream>
using namespace std;class Base {
public:
int x;
};
class Derived : private Base {
public:
void setValue() {
x = 20;
}
void show() {
cout << x;
}
};
int main() {
Derived d1; // d1.x = 20; // not allowed
d1.setValue();
d1.show();
return 0;
}
Output:
20
3. Protected Inheritance
Description
जब base class को protected रूप में inherit किया जाता है, तो:
- base class के public और protected members → protected बन जाते हैं
- private members → accessible नहीं होते
Example
#include <iostream>
using namespace std;class Base {
public:
int x;
};
class Derived : protected Base {
public:
void setValue() {
x = 30;
}
void show() {
cout << x;
}
};
int main() {
Derived d1;
// d1.x = 30; // not allowed
d1.setValue();
d1.show();
return 0;
}
Output:
30
Summary Table
| Inheritance Type | Public Members | Protected Members | Private Members |
|---|---|---|---|
| Public | Public | Protected | Not Accessible |
| Private | Private | Private | Not Accessible |
| Protected | Protected | Protected | Not Accessible |
Important Points
- Private members कभी भी directly inherit नहीं होते
- Access specifier inheritance behavior को control करता है
- Public inheritance सबसे ज्यादा उपयोग किया जाता है
- Private inheritance में external access बंद हो जाता है
निष्कर्ष
Public, Private और Protected inheritance C++ में access control को निर्धारित करते हैं। यह तय करते हैं कि base class के members derived class में कैसे behave करेंगे। सही inheritance type का चयन program की security और structure दोनों को प्रभावित करता है।