Constructor:
Constructor are the member function that are executed automatically. When an object is created, no explicit call is necessary to involve them through the dot operator.It is called constructor because it construct the value of data member of the class. Constructor are mainly used for data initialization.
Class class name
{private:
.......................
public:
class name([parameter])
{ body of function;
}
};
Example:
Class student
{int roll;
public:
student()
{
}
void getdata()
{cin>>roll;
};
void main()
{
student s;
s.student(); //error
s.getdata();
}
Types of Constructor:
There are basically three type of constructor:-
1. Default Constructor:
2. User Defined Constructor:
3. Copy Constructor:
1. Default Constructor:
The Constructor that accept no parameter is called default constructor.it is also known as implicit constructor because compiler provide a default constructor that has no argument. The default constructor perform no processing other than reservation of memory. This constructor is always called by compiler if no user defined constructor is provided and the constructor is automatically called when an object is created.
Syntax:
Class name()
{
}
Example:
Class test
{ int count;
public:
test(){
}
void getcount()
{
cin>>count;
}
void displaycount()
{
cout<<count;
}
}; // end of class
void main()
{ test t[50];
int i;
for(i=0;i<=50;i++)
{ t.getcount();
t.displaycount();
}
getch();
} // end of program
2. User Defined Constructor:
If initialization of data of an object is required while creating an object,then the programmer has to define its own constructor for that purpose.The code of a user defined constructor does not actually cause memory to be reserved for the data because it is still done by default constructor automatically. The user defined constructor may take argument. The main advantage of user defined constructor is to initialize the object while it is created.
Example:
Class test
{int num;
public:
test(int x)
{num=x;
}
void display()
{cout<<num;
}
}; // end of class
void main()
{ test t1(7);
test t2(12);
test t3(100);
t1.display(); // 7
t2.display(); //12
t3.display(); //100
getch();
} // end of program
3. Copy Constructor:
Constructor having a reference parameter is known as copy constructor.The copy constructor creates an object as an exact copy of another object in term of its attribute.In copy constructor,newly instantiated object object equal another existing object of same class.The copy constructor are also called using assignment operator or object as argument.
Example:
Class test
{int id;
public:
test(){ // default constructor
}
test(int a) // user defined constructor
{ id=a;
}
test(test &x)
{
id=x.id;
}
void display()
{cout<<id;
}
}; // end of class
void main()
{
test t(5);
test t1=t;
test t2(t);
t.display(); // 5
t1.display(); // 5
t2.display(); //5
getch();
} // end of program
No comments:
Post a Comment