Monday, 8 August 2011

Constructors and Destructors

1. What is Constructors?





3. when to use the constructors
4. Destructors



 

Constructor is a special member functions
, which is used to initialize the data into the object



Important points about constructors:

1.      Constructor is a    member functions  that is executed automatically whenever an object is created.
2.      Constructor will return nothing, not even void.
3.      If no such constructor is defined then the compiler supplies a default constructor.
4.      Constructors should be declared in public section.
5.      Constructors cannot be inherited, though a derived class can call the base class constructor.
6.      Like other C++ functions Constructors can have default arguments.
7.      Constructors cannot be virtual.
8.      When a constructor is declared for a class, initialization of class objects become mandatory.
9.      Constructors are the special member functions that  allow same name as that of the class name
10.  Constructors allow you to initialize the values into a instances, variables of objects.
11.  Constructors are invoked when the objects of class are created.
12.  Constructors can be overloaded.
13.  Constructors of class is invoked in two ways
                                                              i.      explicitly
                                                            ii.      implicitly
Example1:

class A
{
private:
int m, n;
public:
A( );   //constructor declared
};

A: :A( )          //constructor defined; it has same name as its class name; it has no return type.
{
m=0;
n=0;
}

Void main()
{
A a1;
}

Explanation of the above example:

When a class contains the constructor like the defined above, it is guaranteed that an object created by the class will be initialized automatically.

For example the declaration     A aObj;   

Object aObj is created. Not only creates the object but also initializes its data members m and n to zero.

There is no need to write any statement to invoke the constructor as we do with the normal member functions.
If a normal member function is defined for zero initialization, we need to invoke this function (Constructor) for each of the objects separately, and this would become inconvenient if there are large numbers of objects.

The default constructor for class A is A::A()

Example 2:

#include<iostream.h>
class Integer
{
private:
int i;
public:
void  getdata()
{
cout<<”endl<<”enter any integer”;
cin>>i;
}

void setdata (int j)
{
i=j;
}

Integer()                       //0 argument (or) default constructor
{
}
Integer (int j)               //single parameter constructor
{
i=j;
}
void display()
{
cout<<endl<<”value of i”<<i;
}
};

void main ()
{
Integer i1; // zero argument constructor will be called.
Integer i2(10);  // single argument constructor will be called.
}



Constructors
Constructors are categorized in 4 types 

You may like the following posts:



No comments:

Post a Comment