सी++ बहुरूपता
बहुरूपता
बहुरूपता का अर्थ है "कई रूप", और यह तब होता है जब हमारे पास कई वर्ग होते हैं जो विरासत से एक दूसरे से संबंधित होते हैं।
जैसा कि हमने पिछले अध्याय में निर्दिष्ट किया था; वंशानुक्रम हमें किसी अन्य वर्ग से विशेषताओं और विधियों को प्राप्त करने देता है। बहुरूपता विभिन्न कार्यों को करने के लिए उन विधियों का उपयोग करता है। यह हमें एक ही क्रिया को विभिन्न तरीकों से करने की अनुमति देता है।
उदाहरण के लिए, एक बेस क्लास के बारे में सोचें, जिसे Animal
एक मेथड कहा जाता है animalSound()
। जानवरों के व्युत्पन्न वर्ग सूअर, बिल्ली, कुत्ते, पक्षी हो सकते हैं - और उनके पास एक पशु ध्वनि (सुअर ओंक, और बिल्ली म्याऊ, आदि) का अपना कार्यान्वयन भी है:
उदाहरण
// Base class
class Animal {
public:
void
animalSound() {
cout << "The animal makes a sound \n"
;
}
};
// Derived class
class Pig : public Animal {
public:
void
animalSound() {
cout << "The pig says: wee wee \n" ;
}
};
// Derived class
class Dog
: public Animal {
public:
void animalSound()
{
cout << "The dog says: bow wow \n" ;
}
};
इनहेरिटेंस चैप्टर से याद रखें कि हम :
एक क्लास से इनहेरिट करने के लिए सिंबल का इस्तेमाल करते हैं।
अब हम बना सकते हैं Pig
और ऑब्जेक्ट कर सकते हैं और विधि
Dog
को ओवरराइड कर सकते हैं:animalSound()
उदाहरण
// Base class
class Animal {
public:
void
animalSound() {
cout << "The animal makes a sound \n"
;
}
};
// Derived class
class Pig : public Animal {
public:
void
animalSound() {
cout << "The pig says: wee wee \n" ;
}
};
// Derived class
class Dog
: public Animal {
public:
void animalSound()
{
cout << "The dog says: bow wow \n" ;
}
};
int main() {
Animal
myAnimal;
Pig myPig;
Dog myDog;
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
}
"विरासत" और "बहुरूपता" का उपयोग क्यों और कब करें?
- यह कोड पुन: प्रयोज्य के लिए उपयोगी है: जब आप एक नया वर्ग बनाते हैं तो मौजूदा वर्ग की विशेषताओं और विधियों का पुन: उपयोग करें।