कंस्ट्रक्टर ओवरलोडिंग- एक क्लास में एक से ज्यादा कंस्ट्रक्टर हो सकते हैं और इसे कंस्ट्रक्टर ओवरलोडिंग कहा जाता हैं।
प्रोग्राम- कंस्ट्रक्टर ओवरलोडिंग
#include<iostream>
using namespace std;
class point
{
int x,y;
public:
point () // no argument constructor
{
x=0;
y=0;
}
point (int a) // one argument constructor
{x=y=a; }
point (int m, int n)//two arguments constructor
{
x=m;
y=n;
}
void show()
{
cout<<"x="<<x<<"\n";
cout<<"y="<<y<<"\n";
}
};
int main()
{
point p1;
point p2 (5);
point p3 (7,11);
cout<<"Coordinates of p1 are\n";
p1. show ();
cout<<"Coordinates of p2 are\n";
p2 . show ();
cout<<"Coordinates of p3 are\n";
p3. show ();
return 0;
}
प्रोग्राम का आउटपुट होगा
Coordinates of p1 are
x=0
y=0
Coordinates of p2 are
x=5
y=5
Coordinates of p3 are
x=7
y=11
उपरोक्त प्रोग्राम में, क्लास point में तीन कंस्ट्रक्टर हैं। पहला बिना आरग्यूमेन्ट का कंस्ट्रक्र है। इसका उपयोग बिना किसी प्रारंभिक वेल्यू का ऑब्जेक्ट बनाने के लिए किया जाता है। जब हम अन्य कंस्ट्रक्टर परिभाषित करते हैं तब हमें कम्पाइलर को संतुष्ट करने के लिए बिना आरग्यूमेन्ट का कंस्ट्रक्टर परिभाषित करना होगा। दूसरा कंस्ट्रक्टर एक वेल्यू पैरामीटर के रूप में लेता है और ऑब्जेक्ट को इनिशियलाइज करता है। तीसरा कंस्ट्रक्टर दो आरग्यूमेन्ट लेता है और इन दो वेल्यू से ऑब्जेक्ट को इनिशियलाइज करता है।