Class Constructors and Destructors in C++


Class Constructors and Destructors
What is a Constructor?
A class constructor is a special function in a class that is called when a new object of the class is declared. It therefore provides the opportunity to initialize objects as they are created and to ensure that data members only contain valid values.
·                     constructor purpose is to initialize data members
·                     it is not explecitly call
·                     It is  automatically call so it have no return type
·                     Constructor does not have return type
·                     It has same name as class name
You have no leeway in naming a class constructor - it always has the same name as the class in which it is defined.. It also has no return type. It's wrong to specify a return type for a constructor; you must not even write it as void. The primary function of a class constructor is to assign initial values to the data elements of the class, and no return type is necessary .

Constructor for class rational is

rational (  ):num( 1 ) , denum( 1 )
        { }

Constructor for class distance is

distance ( ): feet( 0) , inches ( 0.0 )
     { }

Here an example of rational class will clear your idea , very easy


#include <iostream>
using namespace std;
class rational
{
private:
            int num;
            int dnum;
public:
            rational():num(1),dnum(1)
            {}
            void get ()
            {
                        cout<<"enter numerator";
                        cin>>num;
                        cout<<"enter denomenator";
                        cin>>dnum;
            }
            void print ()
            {
                        cout<<num<<"/"<<dnum<<endl;
           
           
            }
           
};
void main ()
{
            rational r1;

            r1.get();
           
         r1.print();
           
}


This example will clear your idea about constructor which initializes values to data members as we first use setval( ) function.


Destructor:
A constructor _  is called automatically when an object is first created. you can guess that another function is called automatically when an object is destroyed .such a function is called destructor.
·                     It is automatically call
·                     No return type
·                     same name as class name which same as constructor but with a tilde sign
·                     It does not take any parameter so it can not be overloaded.        // can destructor be overloaded ?
A destructor has same name as constructor which is same as class name but destructor is repersented by sign tilde ( ~ ).
Class foo
{
private:
int data;
public:
foo ( ) : data ( 0 )          // constructor
{ }
~ foo ( )                     // destructor        , it does not take any parameter
{ }
};