Wednesday, 18 December 2013

Oops with c+

Constructors:
       Constructors are the special functions that has the same name as that of class.They are used to initialize the class objects.When an object is created,the constructor function begins to be executed.
There is no need to call the function.

Syntax:
class_name()
         {
         
               //Body of constructor
          }


Types of constructors:
  • Default constructors
  • Parameterised constructor
  •  Copy constructor
Default constructor:

The constructor which doesn't have any arguments is called as default constructor.
Example:

sample()
{

}
Parameterised constructor:

The constructor which has arguments is called as parameterised constructor.A call to such a constructor can be done by creating objects with some values.

Example:

sample(int x,int y)
{


}

Copy constructor:
  A copy  constructor can be identified by ampersand symbol.

Syntax:
Class_name(class_name &obj)
{
       //body of constructor
}
Example:
sample(sample &s)
{

         //Body of constructor
}

Sample program to illustrate different types of constructors:

#include<iostream.h>
#include<conio.h>
class sample
{
     private:
          int a,b;
     public:
            /*Default constructor*/
             sample()
             {
                 a=0;
                 b=0;
              }
              /*Parameterised constructor*/
              sample(int x,int y)
              {
                     a=x;
                     b=y;
              }

};
void main()
{
    sample s(10,20);
    int c;
   c=a+b;
   cout<<"The addition is"<<c;
   getch();
}

Sample output:
The addition is 30


 
 




No comments:

Post a Comment