Constructor and Destructor
Constructor and Destructor
INTRODUCTION
So far we saw that, we use member functions to assign the values to the objects. Example: X.getdata(10,20); After the objects are created, then the value initialization occurs But these function can not be used to initialize the member variables at the time of creation of the objects. C++ provides a special member function that is used to initialize the objects during their creation. That is known as the constructor.
INTRODUCTION
Similarly, another member function is used to destroy the objects. That is known as destructors.
CONSTRUCTORS
Its name is the same as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructors as its constructs/initializes the objects of the class. class integer{ int m,n; public: integer(void){m=n=0;}
};
If now any object is created it will be initialized automatically.
DEFAULT CONSTRUCTOR
Till now we are using this type of statement to create objects: student A;
Ex: student::student()
If no constructor is defined explicitly the compiler supplies default constructor.
The constructor should be declared in the public section, and do not have any return types.
PARAMETERIZED CONSTRUCTORS
Rather than using 0s we can use other numbers to assign them as a value.
PARAMETERIZED CONSTRUCTORS
Passing parameters can be done in two ways:
PARAMETERIZED CONSTRUCTORS
class integer{ int m,n; public: integer(void){ m=n=0;} integer(int x, int y){ m=x; n=y;} integer(int p) { m=n=p;} void display(){ cout<<m and n<<m<<n;}}; int main(){ integer i1, i3(0,100); integer i2=integer(20); i1.display(); i2.display(); i3.display(); return 0; }
PARAMETERIZED CONSTRUCTORS
We can not pass object of the same class as parameters.
COPY CONSTRUCTOR
Copy constructor initializes the objects during their creation by using/copying the values of another objects of its own class. class integer{ int m,n; public: integer(void){ m=n=0;} integer(int x, int y){ m=x; n=y;} integer(integer &i) { m=i.m; n=i.n;} }; int main(){ integer i1, i2(10,20); integer i3(i2); return 0; }
DESTRUCTORS
It is used to destroy the objects that have been created by a constructor.
DESTRUCTORS
int count =0; class alpha {
DESTRUCTORS
int main(){ cout<<\n Enter main;
Output: No. of object created = 1 No. of object created = 2 No. of object created = 3 No. of object created = 4 Enter block1 No. of object created = 5 No. of object destroyed =5 Enter block2 No. of object created = 5 No. of object destroyed = 5 Re- Enter Main No. of object destroyed = 4 No. of object destroyed = 3 No. of object destroyed = 2 No. of object destroyed = 1