Thursday, February 17, 2011

Constructor


Constructor:
A ‘constructor’ is a special member function whose task is to automatically initialization of an object of its class. It is special because its name is the same name of the same as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it constructs the values of the data member of the class. The rules for writing constructor functions or its characteristics are:
·         A constructor name must be the same name as that of its class name.
·         It is declared with no return type (not even void).
·         It should have public or protected access within the class.
·         They are invoked automatically when the objects are created.
·         They cannot be inherited, though a derived class can call the base constructors.
·         Like other C++ functions, they have default arguments.
·         Constructors cannot be virtual, cannot refer to their addresses.
·         An object with a constructor (or destructor) cannot be used as a member of a union.
·         They make ‘implicit calls’ to the operator new and delete when dynamic memory allocation is required.

Syntax:
class className
       {
      private:
         ………….
         public:
         className( );                        //constructor
        ………….  };

className :: className( )             //body of the constructor
      {   ………….      }

An example:
class consTest
   {   private:
           int a;
       public:
            consTest()   //constructor
              {  a=100;  }
         
        void display()
            {cout<<"The value of data is\t :"<<a; }
   } ;

 void main()
    {
        consTest obj1,obj2;
          obj1.display();
           obj2.display();       }

Output: The value of the data is        :100
               The value of the data is        :100
Here, the constructor consTest takes no arguments. This type of constructor is called default constructor. 

No comments:

Post a Comment