Constructor and Destructor in C++

Constructor

It is a Special member function whose task is automatic initialization of an object.
It name is same as that of class name.
It is invoked automatically whenever an object of each associated class is created.

constructor is a special method of a class or structure in object-oriented programming that initializes an object of that type.

The role for writing construction function or its features are :

A constructor name must be same as that class.
It should have public or protected access within class.
It can have default argument.
It cannot be inherited those derive class can call the base constructor.
It cannot be virtual.

To see the example click : Example of Constructor

Types of Constructor

a)Default Constructor
b)Parameterized Constructor
c)Copy Constructor



Destructor

It is Used to destroy the object created by constructor
It is a member function whose name is same as class name but is preceded by(~ tilde)
It is a function i.e  automatically executed when the object is destroyed
It get executed whenever an instant of the class to which it belong goes out of existence.
Example: 

#include<iostream>
#include<conio.h>
using namespace std;
int count =0;
class test{
public:
test()
{
count++;
cout<<"\n Number of object created"<<count;
}
~test()
{
cout<<"\n Number of object destroyed"<<count;
count-- ;
}
};
int main()
{
cout<<"\n\n Enter main:";
{
test t1,t2,t3,t4;
{
cout<<"\n\n  Enter block";
test t5;
}
{
cout<<"\n\n Enter Block";
test t6;
}
count<<"\n\n Re-enter main";
}
getch();
}

Output of Constructor



Other C++ Programming:

2 comments:

  1. I know that there are a lot of students who really enjoy the programming. But it’s fair to say that it’s not that easy and quite time-consuming. A good friend of mine recommended me Assignment Expert . They are professionals with a pocket-friendly prices and if you’re trying to avoid doing your homework you should ask them for a help. Btw, they can offer you a help with a lot of different subjects such as Engineering, Economics, Math etc.

    ReplyDelete

Powered by Blogger.