C++ programming language part: 50 Constructor
Constructor
Every object created would have a copy of member data. The
above program, the object K of thwe class nova
had to call a member function called data_in() , there is no possibility
of member data getting initialize automatically. This automac initialization is
performed through the use of constructor functions. So a constructor function
is a special function that is a member of the class and has the same name as
that of the class.
Program 40-1
//class &
object.demo
#include
#include
class
nova //class defined
{ private:
int age; //
we can't type age=30,name[10]=bappi
char name[10]; // so we need a 'constructor'
public:
nova();
//default
constructor
nova(int a, char* b); // defined constructor
void data_in(); //
member function
void data_out();
};
nova::nova()
{
cout<<" Look! It's invocked "<
nova::nova(int a, char* b) // constructor & class would be the same
name
{ a=age;
b=name;
}
void
nova::data_in() //member function
{ cout<<" Type your age
"<
cin>>age;
cout<<"Type your name
"<
cin>>name; }
void nova::data_out() //scope resolution operator
{ cout<<" The age is
"<
cout<<" The name is
"<
void main()
{
nova k;
// k is called
object
k.data_in(); //would
be k->data_in() if pointer
k.data_out();
getch();
}
Program 40_2
//class & object.demo
#include
#include
class
nova //class defined
{
private:
int p1,p2,p3; // we can't type p1=5 likk, need a
'constructor'
public:
nova(); //default constructor
nova(int,int); // defined constructor
void data_in(int,int); // member function
void
sum();
void data_out();
};
nova::nova()
{
cout<<" Look! It's invocked "<
p1=p2=p3=0; }
nova::nova(int x,int y) // constructor & class would be the same
name
{
cout<<" two constructor are called "<
p1=x;
p2=y; }
void
nova::data_in(int a,int b) //member function
{
p1=a;
p2=b;
}
void nova::sum()
{
p3=p1+p2;
}
void nova::data_out() //scope resolution operator
{
cout<<" The sum is=
"<
}
void main()
{
nova k1,k2(4,3),*k3; //
k is called object
k3=new nova(5,10); // new value are assign
k2.sum(); //this
is from initialize member data
k3->sum();
k3->data_out();
k2.data_out();
}
Part- 86 assign the content of twostring
জ্ঞানকোষ প্রকাশনী
৩৮/২-ক, বাংলাবাজার (২য় তলা), ঢাকা।
ফোনঃ ৭১১৮৪৪৩, ৮১১২৪৪১, ৮৬২৩২৫১.
কলকাতায় পরিবেশক/প্রাপ্তিস্থান
রিতা ইন্টারন্যাশনাল
৩৬, পি.এন. ব্যানার্জি রোড, কলকাতা
ফোনঃ ২৫১৩৮৩৫৯, ৯৮৩০৪৩৯৬৭৯, +৯১৯৮৩০৪৩৯৬৭৯