/    /  CPP- Constructor or class constructor

Constructor or class constructor

 

A class constructor is a special member function of a class that is executed whenever a new object of that class is created. A constructor will have exactly the same name as the class name and there is no return type at all, not even void. 

 

Constructors can be very helpful to initialize every object. Constructors can be defined either in the class definition or out of the class definition using the class name and the scope resolution operator (::).

 

Example Program:

#include<iostream>
using namespace std;
class A
{ 
int i, j;
 public:
 A();//Constructor declared
 void show();
};
A :: A() //constructor definition
{ i = 0;
 j = 0;
}
void A::show()
{ 
 cout<<"i = "<<i << endl;
 cout<<"j = "<<j << endl;
}
int main( )
{
 A a; // a is object and i =0
 a.show(); //calling show() with object a
 return 0;
}

 

Output:

 

Characteristics

  1. They should be made public.
  2. They are called automatically upon creation of objects.
  3. They do not have a return type, not even a void and they cannot return values.
  4. These may have default arguments.
  5. We do not have access to their addresses.
  6. They perform implicit calls to new operators and remove when memory is required
  7. Constructors are not meant to be virtual.