What is constructor and destructor in C++

Introduction to Constructor

·               A constructor is a member function

·        Constructor has the same name as the class name

·        Constructor cannot return values

·        It is automatically called when an object is created.

 

Type of constructor

·        Parameterized constructor

·        Copy constructor

·        Default constructor

 

Introduction to Destructor

·                Destructor are used to de-allocate memory

·        They are called when object is destroyed

·        A destructor takes no arguments and has no return type

 

Eg:- parameterize constructor and destructor

#include<iostream>
using namespace std;

class Addition
{
int a, b;
public:
//here Parameterize constructor created
Addition(int, int);
//here destructor create, it is automatically called when constructor called.
~Addition();
int add()
{
return(a + b);
}
};
Addition::Addition (int x, int y)
{
a = x;
b = y;
};
Addition::~Addition ()
{
cout << "memory deallocation\n";
}
int main ()
{
//the constructor that have argument, is called parameterize constructor
Addition obj (3, 4);
cout << "sum " <<obj.add()<<"\n";
return 0;
}
Output:- sum 7
memory deallocation
 
Example of default constructor
#include<iostream>
using namespace std;

class Subtraction{
   public:
    int a,b;
    int sub(int a,int b){
        return(a-b);
    }
//create default constructor
    Subtraction();   
};
//access the default constructor by using scope resolution
Subtraction::Subtraction(){
   
}
int main(){
    Subtraction subtr;
    cout<<"subtraction: "<<subtr.sub(5,9);
}

 Output:- subtraction: -4


Next Post Previous Post
No Comment
Add Comment
comment url