Sunday 8 June 2014

Types of Constructor

                There are three types of constructors in c++.
  1) Default constructor
   2)parametric constructor
   3)Copy constructor


Have a look on this simple program.


#include<conio.h>
#include<iostream>

using namespace std;

class student
{
private:
int marks;
double percentage;
public:
student()  // default constructor
{
marks=0;
percentage=0.0;
}
student(int a, double b)  // Parametric constructor
{
marks = a;
percentage = b;
}
student( student &s)  // copy constructor
{
marks=s.marks;
percentage=s.percentage;
}
void show()
{
cout<<"\n marks ="<<marks;
cout<<"\n percentage ="<<percentage;
}
};

int main()
{
student s1;  // calling default constructor
s1.show();
student s2(95,95.6);  // calling parametric constructor
s2.show();
student s3(s2);  // calling copy constructor
s3.show();
getch();
return 0;
}


Parametric ConstructorIn order to initialize various data elements of different objects with different values when they are created. C++ permits us to achieve this objects by passing argument to the constructor function when the object are created . The constructor that can take arguments are called parameterized constructors



Copy constructor: A constructor is a constructor that creates a new object using an existing object of the same class and initializes each data member of newly created object with corresponding data member of existing object passed as argument. since it creates a copy of an existing object so it is called copy constructor.

 

No comments:

Post a Comment