Constructors and its types
Definition: A constructor is a special member function whose task is to initialise the object of its class.It is special because its name same as the class name .Constructor will be invoked whenever an object of its associated class is created.It is called constructor because it constructs the values of the data members of the class.
Constructor should have some special characteristic:
1. They should be compulsory declared in the public section
2. These constructors are invoked automatically when the objects are created.
3. They do not have any return types,not even a void keyword or function and therefore,and they cannot return any values.
4. They cannot be inherited ,though a derived class can call the base class constructor.Like other c++ functions,they can have default arguments.
5. Constructors cannot be virtual.We cannot refer to their addresses.
6. An object with constructor(or destructor) cannot be used as a member of union.
7. They make implicit calls to the operators new and delete when memory location is required.
8. An explicit call to the constructor for an existing object is forbidden
There are total four types of constructors in C++ language they are:
1.Default Constructor
2. Parameterised Constructor
3. Overloaded constructor
4.Copy Constructor
1. Default constructor: Constructor without arguments are called as default constructor.
Program to Understand the Default Constructor:
#include<iostream>
using namespace std;
class simple
{
private :
float p,n,r,s;
public :
simple()
{
p = 2000;
n = 3;
r = 2.5;
}
void show()
{
cout<<"p : "<<p<<endl;
cout<<"n : "<<n<<endl;
cout<<"r : "<<r<<endl;
}
void process()
{
s = (p * n * r)/100;
}
void output()
{
cout<<"Simple Interest : "<<s<<endl;
}
};
int main()
{
simple s;
s.show();
s.process();
s.output();
return 0;
}
2. Parameterised Constructor: The constructor which take arguments are called as parameterised constructor.
Program to understand the parameterised constructor:
#include<iostream>
using namespace std;
class rect
{
private :
float l,b,a,p;
public :
rect(int x,int y)
{
l = x;
b = y;
}
void show( )
{
cout<<"Length = "<<l<<endl;
cout<<"Breadth = "<<b<<endl;
}
void show( )
{
cout<<"Length : "<<l<<endl;
cout<<"Breadth : "<<b<<endl;
}
void process( )
{
a = l * b;
p = 2 * (l + b);
}
void output( )
{
cout<<"Area = "<<a<<endl;
cout<<"Perimeter = "<<p<<endl;
}
};
int main( )
{
rect r(20,30);
r.show( );
r.process( );
r.output( );
return 0;
}
0 Comments