What is the purpose of a constructor in OOP?
2025
What is the purpose of a constructor in OOP?
- A.
To destroy objects
- B.
To create instances of abstract classes
- C.
To initialize object properties
- D.
To define abstract methods
Attempted by 146 students.
Show answer & explanation
Correct answer: C
In Object-Oriented Programming (OOP), a constructor is a special method that is automatically called when an object of a class is created. Its primary purpose is to initialize the object's properties with default or provided values. Constructors ensure that objects start in a valid and consistent state.
Key points about constructors:
Constructors are not used to destroy objects — that is the role of destructors in some languages.
Constructors cannot create instances of abstract classes because abstract classes cannot be instantiated.
Constructors do not define abstract methods — abstract methods are declared in abstract classes and implemented in derived classes.
Therefore, the correct purpose of a constructor is to initialize object properties.
हिन्दी उत्तर:
ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग (OOP) में, कंस्ट्रक्टर एक विशेष विधि है जो क्लास के ऑब्जेक्ट के निर्माण के समय स्वचालित रूप से कॉल की जाती है। इसका मुख्य उद्देश्य ऑब्जेक्ट की प्रॉपर्टीज़ को डिफ़ॉल्ट या प्रदान किए गए मानों के साथ शुरू करना है। कंस्ट्रक्टर यह सुनिश्चित करते हैं कि ऑब्जेक्ट एक मान्य और सुसंगत अवस्था में शुरू हों।
कंस्ट्रक्टर के बारे में मुख्य बिंदु:
कंस्ट्रक्टर ऑब्जेक्ट्स को नष्ट करने के लिए नहीं उपयोग किए जाते हैं — कुछ भाषाओं में डिस्ट्रक्टर्स का यह काम होता है।
कंस्ट्रक्टर एब्स्ट्रैक्ट क्लास के इंस्टेंस नहीं बना सकते क्योंकि एब्स्ट्रैक्ट क्लास को इंस्टेंसिएट नहीं किया जा सकता।
कंस्ट्रक्टर एब्स्ट्रैक्ट मेथड्स को परिभाषित नहीं करते — एब्स्ट्रैक्ट मेथड्स एब्स्ट्रैक्ट क्लास में घोषित किए जाते हैं और व्युत्पन्न क्लास में वास्तविकीकृत होते हैं।
इसलिए, कंस्ट्रक्टर का सही उद्देश्य ऑब्जेक्ट प्रॉपर्टीज़ को प्रारंभ करना है।