Tuesday 1 October 2013

constructors

Constructors
 constructors are the special data member of the class,
they have some special property are as follows:-
1) Same name of the class name .
2) have no return type.
3) No need to call in the main ,they get called when the object  is created.
General form of the constructor is :-
class name ()
{
body of the constructor
}
there are three types of constructor

1) default constructor
2) parameterised constructor

3)copy constructor
1) Default cons

   consider the following code
#include < iostream.h>
#include <conio.h>
class Sample
{
int num;

Sample ()        //constructor
{
cout<<"constructor called"<<num;
}
};
void main()
{
Sample ob;
getch();
>>>>>>>>>>>Copy constructor<<<<<<<<<<<<<<<<
It is used to Copy one object into another



classname ( Class Name   & Object name)
{
body
}

Eg-->

class Sample
{
int i;
public:
Sample()        //default
{
i=0;
}
Sample(int a)   //parameterised
{
i=a;
}

Sample( Sample &ob)  //copy cons
{
i = ob.i;
}

No comments:

Post a Comment