Pages

Thursday, 22 February 2018

Constructor and Destructor in C++ Programming Language


Types of Constructor
A constructor that accepts no parameters is known as default constructor. If no constructor is defined then the compiler supplies a default constructor.

Circle :: Circle()
{
    radius = 0;
}
Parameterized Constructor -: A constructor that receives arguments/parameters, is called parameterized constructor.

Circle :: Circle(double r)
{
    radius = r;
}
Copy Constructor-: A constructor that initializes an object using values of another object passed to it as parameter, is called copy constructor. It creates the copy of the passed object.
Circle :: Circle(Circle &t)
{
    radius = t.radius;
}
Destructor
A destructor is a member function having sane name as that of its class preceded by ~(tilde) sign and which is used to destroy the objects that have been created by a constructor. It gets invoked when an object’s scope is over.

~Circle() {}

#include<iostream>
using namespace std;

class Circle //specify a class
{
    private :
        double radius; //class data members
    public:
        Circle() //default constructor
        {
            radius = 0;
        }
        Circle(double r) //parameterized constructor
        {
            radius = r;
        }
        Circle(Circle &t) //copy constructor
        {
            radius = t.radius;
        }
        void setRadius(double r) //function to set data
        {
            radius = r;
        }
        double getArea()
        {
            return 3.14 * radius * radius;
        }
        ~Circle() //destructor
        {}
};

int main()
{
    Circle c1; //defalut constructor invoked
    Circle c2(2.5); //parmeterized constructor invoked
    Circle c3(c2); //copy constructor invoked
    cout << c1.getArea()<<endl;
    cout << c2.getArea()<<endl;
    cout << c3.getArea()<<endl;
    return 0;
}

Another way of Member initialization in constructors
Circle :: Circle(double r)
{
    radius = r;
}
It could also be defined using member initialization as:

Circle :: Circle(double r) : radius(r)

{}