What are Constructors and Destructors ?

Class is a user defined data type that behave very similar to built-in data types.
We should able to initialize a class type variable (object) when it is declared much the same way as an ordinary variable,
                int a=10;
Similarly, when a variable of built-in data type goes out of scope the compiler automatically destroys the variable.
C++ provide special member functions called constructor and destructor that used to initialize and destroy objects.

Constructors

A constructor is a special member function whose task is to initialize the objects of its class. It have some special characteristics
  1. The name of constructor is same as class name. 
  2. it should be declared in public section. 
  3. it is invoked automatically when the objects are created. 
  4. it do not have any return type, so it cannot return values. 
  5. it can’t be inherited, though a derived class can call the base class constructor. 
  6. it can’t be virtual.
  7. it can have default arguments.
A constructor can be declared and defined as follows:
class integer
{
         private:
         int m,n;
         public:
         integer() // constructor defined
        {
              m=0,n=0;
         }
};
integer a; // object created and initialized


Post a Comment

Previous Post Next Post