Parameterized constructor in C++

We know that in C++ language default constructor will provide initial value to class object but it initializes all the objects of class by same value. If programmer wants to initialize class objects with different values then he/she can use parameterized constructor. In other words, we can say that “A constructor which accept parameter as input and initialize it’s values to class object is called parameterized constructor”.
हमे ज्ञात है कि C++ में डिफ़ॉल्ट कंस्ट्रक्टर द्वारा क्लास के डाटा मेम्बर्स को प्रारंभिक मान प्रदान किया जाता है परन्तु यह सभी ऑब्जेक्ट को एक समान मान प्रदान करता है। यदि प्रोग्रामर भिन्न-भिन्न क्लास ऑब्जेक्ट को भिन्न-भिन्न प्रारंभिक मान प्रदान करना चाहता है तब वह पैरामीटराईज्ड कंस्ट्रक्टर का प्रयोग करता है। दुसरे शब्दों में हम कह सकते है कि"एक कंस्ट्रक्टर जो इनपुट में आर्गुमेंट ग्रहण करता है एवं उनसे ऑब्जेक्ट के डाटा मेम्बर को प्रारंभिक मान प्रदान करता है पैरामीटराईज्ड कंस्ट्रक्टर कहलाता है।"  
          
Syntax:-
public:
class_name (arg1, arg2,......, argn){
statements/initialization;
 ............
 ............
};

Example:-
C++ program for Parameterized Constructor.

#include<iostream.h>
#include<conio.h>
class addition{
float a,b,c;
public:
//parameterized constructor
addition(float m,float n,float o){
a=m;
b=n;
c=o;
}
void display();
void addab();
};
void addition::display(){
cout<<"a="<<a<<endl<<"b="<<b<<endl<<"addition c="<<c<<endl;
}
void addition::addab(){
cout<<"Enter value of a and b"<<endl;
cin>>a>>b;
c=a+b;
cout<<"Additon Completed"<<endl;
}
int main(){
addition y(3.2,5.5,8.7);
clrscr();
y.display();
getch();
y.addab();
getch();
y.display();
getch();
return 1;
}

No comments:

Post a Comment