Wednesday, March 28, 2018

Write a C++ program to illustrate the use of constructors and destructors (by using above programs)


AIM: Write a C++ program to illustrate the use of constructors and destructors (by using above programs)
THEORY:
               Constructors and destructors are fundamental to the   concept in      C++.both constructor and destructor are more or less like normal functions (but with some differences) that are    provided to enhance the capabilities of a class.
          Constructor, as the name suggests is used to allocate memory (if required) and construct the objects of a class while destructor is used to do the required clean-up when a class object is destroyed. In this article, we will study the concept of constructors and destructors through working examples.
As we have already discussed that a constructor is used for creating an object. In precise terms, a constructor is a special function that gets called automatically when the object of a class is created. Similarly, a destructor is a special function that gets called automatically when a class object is deleted or goes out of scope.
Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors iitialize values to object members after storage is allocated to the object.
class A
{
 int x;
 public:
 A();  //Constructor
};
While defining a contructor you must remeber that the name of constructor will be same as the name of the class, and contructors never have return type.
Constructors can be defined either inside the class definition or outside class definition using class name and scope resolution :: operator.
SOURCE CODE:
#include<iostream>
using namespace std;
class dist{       
            public:
            int feet,inch;
            dist(){  }
            dist (int x,int y){
                        feet=x;
                        inch =y;
            }
            dist (float m,float n)    {
                        feet=m;
                        inch=n;
            }
            void display()  {
            }         
            void sum(dist obj1,dist obj2)  {
                        feet=obj1.feet+obj2.feet;
                        inch=obj1.inch+obj2.inch;
                        if(inch>=12)                {
                                    feet=feet+1;
                                    inch=inch-12;
                        }
            }
            ~dist() {
                        cout<<"\n object deleted:";
            }
};
int main(){
            dist obj1(8,9),obj2(4.0f,7.3f),obj3;
            obj3.sum(obj1,obj2);
            obj3.display();
}

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home