C++ Polymorphism In Hindi

📔 : C++ 🔗

C++ में, polymorphism का अर्थ है many forms , यह यह एक geek भाषा का शब्द है दो शब्दों में मिलकर बना हुआ है poly(many) और forms . सरल शब्दों में कहें तो , polymorphism का मतलब है बहुत सारी forms का होना।


Polymorphism एक ability है जिसके द्वारा एक तरह के task को आप different - different तरीके से कर सकते हैं। इस concept को normally Inheritance में use किया जाता है।

C++ Polymorphism Type

polymorphism को दो तरह से को achieve किया जाता है -

  1. Run Time Polymorphism
  2. Compile Time Polymorphism

C++ Run Time Polymorphism

इस प्रकार के Polymorphism को Method Overriding के द्वारा achieve किया जाता है। इसमें object method को base class के अलावा child class में भी define कर दिया जाता है ,जैसा कि आप पिछले topic में पढ़ा चुके हैं।

C++ Run Time Polymorphism Example

CopyFullscreenClose FullscreenRun
#include <iostream>
using namespace std;

// define base class
class Food {
  public:
  void eat() {
    cout << "Eating Food \n" ;
  }
};

// Derived class
class Paneer : public Food {
  public:
  void eat() {
    cout << "Eating Paneer \n" ;
  }
};

// Another derived class
class Daal : public Food {
  public:
  void eat() {
    cout << "Eating Daal \n" ;
  }
};

int main() {
  Food foodObj;
  Paneer paneerObj;
  Daal daalObj;

  foodObj.eat();
  paneerObj.eat();
  daalObj.eat();
  return 0;
}
Output
Eating Food 
Eating Paneer 
Eating Daal 

C++ Compile Time Polymorphism

इस प्रकार के polymorphism को Method Overloading / Operator Overloading के द्वारा achieve किया जाता है। इसे static या Early Binding भी कहते हैं क्योंकि इसमें parameter compile time bind होते हैं। Overloaded Methods को return type और pass किये गए arguments की संख्या के according compile time में invoke किया जाता है। इसमें compiler , compile time में decide करके सबसे appropriate method को select करता है।

C++ Compile Time Polymorphism Example

CopyFullscreenClose FullscreenRun
#include <iostream>
using namespace std;
class Calculate {
	public:
	int sum(int num1, int num2){
		return num1+num2;
	}

	// define same name method with different parameters.
	int sum(int num1, int num2, int num3){
		return num1+num2+num3;
	}
};

int main() {
	Calculate obj;
	cout << "Output: " << obj.sum(10, 10) << endl;
	cout << "Output: " << obj.sum(20, 20, 30);
	return 0;
}
Output
Output: 20
Output: 70

ऊपर दिया गया Example देखकर आप समझ सकते हैं कि , किस तरह से method overloading का use करके compile time polymorphism को achieve किया गया है। I Hope, आपको C++ में Polymorphism के बारे में अच्छे से समझ आया होगा।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers