Thursday, March 17, 2016

Constructors in C++

Constructors in C++ 


Dear Folks.. 
A constructor is a method/member function
which constructs an object. Since an object is user defined variable, there must be some special way to allocate memory for it. This task of allocating, required amount of memory for an object and setting-up it's initial values, is done by this special method/member function.

It is special, as it has method name as class-name for which it is being defined.
The basic characteristics of a constructor are...
  • method name same as class-name
  • has no return type, not even as void
  • called automatically when an object is created
  • usually defined with public scope
  • can not be defined as virtual for polymorphism
Types of constructors: Broadly we find three types of constructors namely
  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor
Default Constructor: It is responsible for allocating memory for an object which has no parameters. It is characterizied with no arguments in the definition.
If the class has not defined any constructor for it's objects, then the compiler supplies this constructor, hence the name default. Bear in mind, if you define some type of constructor, without defining default constructor, assuming that, the compiler supplies it, this will not work, if you are creating an object without args,some where in the program.In this case, the default constructor must be defined by you.

Parameterized constructor: It is used to create and initialize objects with arguments. Usually it is used to initialize instance variables.

Copy constructor: It is used to copy states of one object into another object which is being created. It performs deep copy(makes a copy of every state).

// An example to demonstrate all these constructors.
class Account
{
  private:   int acc_no;
             double balance;
  public: /* default constructor*/
          Account(){ acc_no = 100; balance = 500;}
          /* parameterized constructor*/
          Account(int n, double x)
          {
            acc_no = n;
            balance=x;
          }
          /* copy constructor*/
          Account(Account & ax)
          {
            ax.acc_no = acc_no;
            ax.balance =  balance;
          }
          void show()
          {
           cout<<" Account No:"<<acc_no<<endl;
           cout<<" Balance :"<<balance<<endl;
          }
};

void main()
{
  Account a1,a2(121,5000),a3(131,7000);
  Account a4(a2);
  a1.show();
  a2.show();
  a3.show();
  a4.show();
}

output:
Account No:100
Balance :500

Account No:121
Balance :5000

Account No:131
Balance :7000

Account No:121
Balance :5000

If find it useful please share it...

No comments:

Post a Comment