Header Ads

Constructors and destructors

Constructors

Constructors (abbreviated as ctor) are special member functions provided by C++ that enables an object to initialize itself when created. This process is also known as automatic initialization of objects. Following points should be kept in mind when using constructors in the program:
  • It should have same name as its class.
  • It should not have void or any return type.
  • It should be declared in the public section of its class.
  •  It can have default arguments.
  • It can be invoked for a constant but cannot be declared one.
  • It cannot be inherited.
A class needs a constructor, so that the compiler automatically initializes an object as soon as it is created. It can be called anywhere in the program.

Types of constructors

There are three types of constructors:

1. Default constructor

A default constructor does not accepts any parameters. The compiler automatically supplies a default constructor, when a class does not have its explicit constructor. 
Let us take an example of a default constructor.

class x
{
int a;
public:
void input();
};

int main()
{
O.input(); //default constructor
}

2. Parameterized constructor

A parameterized constructor hides the default constructor (cannot be invoked) and accepts parameters. When a class have two or more constructors, this case (multiple constructors) is called constructor overloading.
Let us take an example of a parameterized constructor:
class x
{
int a;
public:
void input();
};

int main()
{
O.input(5); //parametrized constructor
}

3. Copy constructor

A copy constructor copies an object of another class. A copy constructor is invokes in the following two conditions:
  • When an object is passed by value:When a function requires a copy of the passed argument to be created for further execution. 
  • When a function returns an object: When an object is returned by a function.
Let us take an example of a copy constructor:
class x
{
int a;
public:
void input();
};

int main()
{
O.input(5); //parametrized constructor  
O1(&O);    //copy constructor               
}
The above example also shows constructor overloading.

Destructors 

A destructor is a member function that is used to destruct the object. It is preceded by the (~) sign.
Following points should be kept in mind when using destructors in the program:
  • It has the same name as the class.
  • It does not takes any arguments and does not have a return type (not even void).
  • It is called by the compiler when the object destroys.
  • It cleans the storage that is not in use.
  • It deinitializes an object when it is no longer required in the program.
  • It should be declared in the public section.
  • Destructors cannot be overloaded, there is only one destructor of a class.
  • It cannot be inherited.
For example if you have a class named hello i.e., class hello then its destructor will be: ~hello.


No comments:

CSE Solved. Powered by Blogger.