MCAWALA

C++ Vertical Menu

C++ Programming Topics

C++ में Inheritance

Inheritance क्या होता है?

Inheritance का मतलब है एक Class का दूसरी Class से गुण (properties) और कार्य (functions) लेना।
इसे हम "विरासत में लेना" कह सकते हैं। इससे कोड दोबारा लिखा नहीं जाता और Code Reuse होता है।

उदाहरण से समझें:

मान लीजिए हमारे पास एक Parent Class है – Animal, और एक Child Class है – Dog
Dog class, Animal class से गुण और कार्य लेती है।

C++ कोड:

#include <iostream>
using namespace std;

// Parent Class
class Animal {
public:
    void eat() {
        cout << "Animal khana kha raha hai." << endl;
    }
};

// Child Class
class Dog : public Animal {
public:
    void bark() {
        cout << "Dog bhauk raha hai." << endl;
    }
};

int main() {
    Dog d1;
    d1.eat();   // Parent class ka function
    d1.bark();  // Child class ka function

    return 0;
}
    

Output:

Animal khana kha raha hai.
Dog bhauk raha hai.
    

सारांश:

  • Inheritance का मतलब है एक class दूसरी class से गुण लेना।
  • Parent Class = Animal (जिससे गुण मिलते हैं)
  • Child Class = Dog (जिसे गुण मिलते हैं)
  • Dog ने Animal का eat() function इस्तेमाल किया।

Types of Inheritance (C++ में):

  • Single Inheritance
  • Multiple Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance