How can one implement the compile-time polymorphism in the C++ programming…
2023
How can one implement the compile-time polymorphism in the C++ programming language?
- A.
By using the template
- B.
By using the concepts of inheritance
- C.
By using both the virtual functions and inheritance
- D.
More than one of the above
- E.
None of the above
Attempted by 353 students.
Show answer & explanation
Correct answer: A
Compile-time polymorphism in C++ is achieved when the decision about which function or class to use is made at compile time. This is typically implemented using templates and function overloading.
Templates allow writing generic functions and classes that can work with different data types without redefining them. For example, a single template function can handle int, float, or custom types, and the compiler generates the appropriate code during compilation.
Function overloading is another form of compile-time polymorphism, where multiple functions with the same name but different parameters are defined. The compiler selects the correct function based on the arguments passed at compile time.
In contrast, runtime polymorphism uses virtual functions and inheritance, where the function call is resolved at runtime. This is not compile-time polymorphism.
Therefore, the correct way to implement compile-time polymorphism in C++ is by using templates.
हिन्दी उत्तर:
C++ में कंपाइल-टाइम पॉलीमॉर्फिज्म तब होता है जब कंपाइलर कंपाइलिंग के दौरान यह तय करता है कि कौन सा फ़ंक्शन या क्लास उपयोग किया जाए। इसे आमतौर पर टेम्पलेट्स और फ़ंक्शन ओवरलोडिंग का उपयोग करके बनाया जाता है।
टेम्पलेट्स ऐसे जनरिक फ़ंक्शन और क्लास लिखने की अनुमति देते हैं जो विभिन्न डेटा प्रकारों के साथ काम कर सकते हैं बिना उन्हें फिर से परिभाषित किए। उदाहरण के लिए, एक टेम्पलेट फ़ंक्शन इंट, फ्लोट या कस्टम प्रकार के साथ काम कर सकता है, और कंपाइलर कंपाइलिंग के दौरान उपयुक्त कोड उत्पन्न करता है।
फ़ंक्शन ओवरलोडिंग एक और कंपाइल-टाइम पॉलीमॉर्फिज्म का रूप है, जहां एक ही नाम वाले कई फ़ंक्शन लिखे जाते हैं लेकिन अलग-अलग पैरामीटर होते हैं। कंपाइलर अलग-अलग आर्गुमेंट्स के आधार पर सही फ़ंक्शन का चयन करता है।
इसके विपरीत, रनटाइम पॉलीमॉर्फिज्म वर्चुअल फ़ंक्शन और इनहेरिटेंस का उपयोग करता है, जहां फ़ंक्शन कॉल रनटाइम पर निर्धारित किया जाता है। यह कंपाइल-टाइम पॉलीमॉर्फिज्म नहीं है।
इसलिए, C++ में कंपाइल-टाइम पॉलीमॉर्फिज्म को टेम्पलेट्स का उपयोग करके सही तरीके से लागू किया जा सकता है।