Constructor in C++
Constructor is a special member function whose task is to initialise the object of its class. It is special because its name is same as the class name. It is called constructor because it construct the value of data members of the class. Constructor is having no return type.
Types of Constructor:
There are 3 types of constructor in C++
1. Default Constructor:
Default constructor is the one which does not accept any value. It is mainly used to initialize the instance variable with the default values. It can also be used for performing some useful task on object creation. A default constructor is invoked implicity by the compiler if there is no constructor defined in the class.
2. Parameterized Constructor:
Parameterized constructor is the one which can initialize the instance variables with the given values. In otherwords, the constructor which can accept the arguments are called parameterized constructor.
3. Copy Constructor:
The constructor which is initializes an object using another object of same class is called copy constructor.
Example of a constructor program:
# include <iostream.h>
# include <conio.h>
class integer
{
int main ;
public ;
integer ( int x, int y ) ; // constructor
declared void display (void )
{
cout << " \n m = " << m << " \n " ;
cout << " \n n = " << n << " \n " ;
}
} ;
integer :: integer ( int x, int y ) // constructor
defined //
{
m = x ;
n = y ;
}
int main ( )
{
clrscr ( ) ;
integer int 1 ( 0,100 ) ;
integer int 2 ( 60,100 ) ;
cout << " \n object 1 " << " \n " ;
int 1.display ( ) ;
cout << " \n object 2 " << \n " ;
int 2.display ( ) ;
getch ( ) ;
return 0 ;
}
Output:
object 1
m = 0
n = 0
object 2
m = 60
n = 75
No comments:
Post a Comment