Constructors and Destructors
Constructors and Destructors
introduction
In all program we have written setdata() function to set values to the objects. And this function must be invoked explicitly by the object. Like object in the real world, objects are created and scraped. There should be a mechanism in the class to do so. So, concept of constructor and destructor is there.
Constructors
It is a special member function whose main operation is to allocated the memory and initialize the objects of the class. it has the same name as class. So, compiler identify it as a constructor. Types of constructor: Default constructor Parameterized constructor Copy constructor Dynamic constructor
Default constructor
A constructor without argument is called Default Constructor. Default constructor called run time when object is created.
Cont..
Parameterized Constructor
Constructor with input parameters are called parameterized constructor. For invoking this constructor, appropriate parameters should be passed while creating object. There are two way to call constructor:
Implicitly called Explicitly called
Cont..(Implicitly called)
Cont..(explicitly called)
Copy constructor
It is used to make copies of the objects. It is generally used to initialize an object from another. It is having following format:
Class_name::class_name(class_name & object)
That is, it is a constructor of class class_name that takes a reference object of the same class as a argument.
Cont..
Copy constructor can be invoked by:
Class_name object1(object2) OR Class_name object1=object2
Cont..
Dynamic Constructor
Object can be created run time. So, memory is allocated run time only. This is called dynamic constructor. That can be achieved by new operator and using pointer.
Cont..
Example:
student *sptr; // does not call any constructor and no memory is allocated.
Cont
Characteristics
They should be declared in the public section. They are invoked automatically when the object is created. They do not have return type, not even void. They can not be inherited, though derived class can call the base class constructor. They can have default argument. They can not be virtual. We can not refer to their address. They implicit call to the new and delete operator when memory allocation is required.
Destructor