Programming Hub C,C++,C#,Asp.Net,Ado.Net,Java,  HTML,SQL.

This Blog Post Only Education Purpose For All Education Related Blogs and Articles Post Here.Download Free Software and Study Materials Mores..

Thursday 29 October 2015

Constructor and Destructor Example with C++

Thank you Visiting In Advance BY IT PROGRAMMING WORLD
Constructor and Destructor Example with C++
Introduction:-
I know C++ is object oriented programming language (OOPs). In OOPs using class and object here class is user defined data type and object is instance of class.  This mean that we should able to initialize a class type variable (object) when it is declared much the same way as initialization of an ordinary variable.
Example    int A=20;
                    float A=5.67; are valid initialization statement for basic data types.
In oops concept constructor is a special member function of class and object.
Constructor:-
Basically simple word you can say create a data memory in a program.
“A constructor is special member function whose task is to initialize objects of its class”. It is special because its name is the same as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor it construct the value of data members of the class.
A constructor is declared and defines as follow below:
//class with a constructor
Class integer
{
Int m,n;
public:
integer (void); //constructor declared
…….
……………………
};
integer :: integer(void) // constructor defined
{
m=0;
n=0;
}
The constructor functions have some special characteristics:
1.      They should be declared in the public section.
2.      They are invoked automatically when the object are created.
3.      A default constructor does not have any parameter but if you need a constructor can have parameters.
4.      This helps you to assign initial value to an object at the time of its creation they do not have return types.
5.      They cannot inherited, through a derived class can call the base class constructor.
6.      Constructor cannot be virtual.
7.      An object with a constructor (or destructor) cannot be used as a member of a union.
8.      They make implicit calls to the operators new and delete when memory allocation required.
Note: - When a constructor is declared for a class, initialization of the class objects become mandatory.
Parameterized Constructor:-
A default constructor does not have any parameter but if you need a constructor can have parameters. This helps you to assign initial value to an object at the time of its creation. C++ permits us to achieve this objective by passing arguments to the constructor function when the objects are created. The constructors that can arguments are called parameterized constructor.

Example below:
Class integer
{
int m,n;
Public:
Integer (int x, int y); //parameterized constructor
……………..
…………
};
integer :: integer(int x, int y)
{
M=x;
N=y;
}
When a constructor has been parameterized, the object declaration statement such as
integer int1;     //may not work.
We just pass the initial values as arguments to the constructor function when an object is declared. This can be done in two methods:
By calling the constructor explicitly.
The following declaration
integer int1= integer (0,100);  //explicit call
This statement creates an integer object int1 and passes the values 0 and 100 to it.

By calling the constructor implicitly.
integer int1= int1(0,100);   //implicit call
This statement called the shorten method, is used very often as it is shorter, looks better the constructor.
Example:
#include<iostream>
using namespace std;
class integer
{
            int m,n;
            public:
                        integer(int, int);  //constructor declared
                        void display(void)
                        {
                                    cout<<"m="<<m<<"\n";
cout<<"n="<<n<<"\n";                        
                        }
};
integer::integer (int x,int y) //constructor defined
{
            m=x;
            n=y;
}

main()
{
            integer int1(0,100);    //implicit call
            integer int2 = integer (25,75);    //explicit call
            cout<<"OBJECT1"<<"\n";
            int1.display();
            cout<<"OBJECT2"<<"\n";
            int2.display();
}
Screenshots Below:

Output below:-


Dynamic Initialization of Constructor:
Class objects can be initialized dynamically too. That is, the initial value of
An object may provide during run time. One advantage of dynamic initialization
Is that we can provide various initialization formats, using overloaded constructors.
This provides the flexibility of using different format of data at run time depending upon the situation.
Consider the long term deposit schemes working in the commercial banks.
The banks provide different interest rates for different schemes as well as for different
Illustrates how to use the class variables for holding account details
and how to construct these variables at run time using dynamic initialization.

Example: Long-term fixed deposit system using dynamic initialization of constructors.
#include<iostream>
using namespace std;
class Fixed_deposit
{
    long int P_amount;    //principal amount
            int Years;            // period of ivestement
            float Rate;           //Interest rate
            float R_value;              //Return value of amount
            public:
                        Fixed_deposit()     //constructor declare
                        {}
                       
                                    Fixed_deposit(long int p, int y, float r=0.12);
                                    Fixed_deposit(long int p, int y, int r);
                                    void display(void);     //using display method
            };
            Fixed_deposit::Fixed_deposit(long int p, int y, float r)   //constructor defined
            {
                        P_amount=p;
                        Years=y;
                        Rate=r;
                        R_value=P_amount;
                        for(int i=1;i<=y;i++)
                        R_value=R_value *(1.0+r);
            }
            Fixed_deposit::Fixed_deposit(long int p,int y, int r)
            {
                        P_amount=P_amount;
                        Years=y;
                        Rate=r;
                        R_value=P_amount;
                        for(int i=0;i<=y;i++)
                        R_value=R_value *(1.0+float(r)/100);
            }
            void Fixed_deposit::display(void)
            {
                        cout<<"\n"<<"Principal Amount="<<P_amount<<"\n"<<"Return Value="<<R_value<<"\n";
            }
            main()

{
            Fixed_deposit FD1, FD2 ,FD3;     //deposit created
            long int p;
            int y;
            float r;
            int R;
            cout<<"Enter Amount,Period,Interest Rate(in percent)"<<"\n";
            cin>>p>>y>>R;
            FD1=Fixed_deposit(p,y,R);
            cout<<"Enter Amount,Period,Interest Rate(in decimal)"<<"\n";
            cin>>p>>y>>r;
            FD2=Fixed_deposit(p,y,r);
            cout<<"Enter Amount,Period,Interest Rate(in percent)"<<"\n";
            cin>>p>>y;
            FD3=Fixed_deposit(p,y);
            cout<<"\nDeposit 1";
            FD1.display();
            cout<<"\nDeposit 2";
            FD2.display();
            cout<<"\nDeposit 3";
            FD3.display();
}


OUTPUT HERE BELOW…

The program uses three overloaded constructors. The parameter values to these constructors are provided at run time. The user can provide input in one of the following forms:
Ø  Amount, period and interest in decimal form.
Ø  Amount, period and interest in percent form.
Ø  Amount and period.
Since the constructors are overloaded with the appropriate parameters, the
One that matches the input values is invoked. For example, the second constructor
Is invoked for the forms (1) and (3), and the third is invoked for the form (2).
Note:-that, for form (3), the constructor with default argument is used. Since input to the third parameter is missing it uses the default value for r.

Copy Constructor:
Copy constructor is used to create a copy of existing object. A copy constructor takes a reference to an object of the same class as itself as an argument. A copy constructor is called following cases.
*      A variable is declared which is initialized from another argument.
*      A value parameter is initialized from its corresponding arguments.
*      An object is returned by a function.
                           The copy constructor takes a reference to a const parameter. It is const to guarantee that the copy constructor doesn’t change it, and it is a reference because a value parameter would require making a copy, which would invoke the copy constructor, which would make a copy of its parameter, which would invoke the copy constructor.
Example of copy constructor:
#include<iostream>
using namespace std;
class code
{
                int id;
                public:
                                code(){}            //constructor
                                code(int a){id=a;}   // constructor again
                                code (code & x)      // copy constructor
                                {
                                                id=x.id;         //copy in the value
                                }
                                void display(void)
                                {
                                                cout<<id;
                                }
                                };
                                main()

{
                code A(100);             //object A is created am initialized
                code  B(A);               //copy constructor called
                code C=A;                 //copy constructor called again
                code D(A);                 //copy constructor called again
                cout<<"\nid of A:";
                A.display();
                cout<<"\nid of B:";
                B.display();
                cout<<"\nid of C:";
                C.display();
                cout<<"\nid of D:";
                D.display();
}

OUTPUT HERE BELOW…



Note:- that a reference variable has been used in the argument to the copy constructor.
We cannot pass the argument by value to a copy constructor.

When no copy constructor is defined, the complier supplies its own copy constructor.
Difference between copy constructor and assignment
A copy constructor is used to initialize a newly declared variable from an existing
Variable. This makes a deep copy like assignment, but it is somewhat simpler:
·         There is no need to test to see if it is being initialized from itself.
·          There is no need to clean up (e.g., delete) an existing value (there is none).
·          A reference to itself is not returned.

Destructors:
                             “Basically simple word you can say destroyed a data memory in a program.”
Destructors are also special member functions used in C++ programming
Language. Destructors have the opposite function of a constructor. The main use of
Destructors are to release dynamic allocated memory. Destructors are used to free
Memory release resources and to perform other clean up. Destructors are automatically
Named when an object is destroyed. Like constructors, destructors also take the same name
As that of the class name.
General Syntax of Destructors

      ~ classname ();
The above is the general syntax of a destructor. In the above, the symbol tilde(~)
represents a destructor which precedes the name of the class.

Some important points about destructors:
·         Destructors take the same name as the class name.
·         Like the constructor, the destructor must also be defined in the public.
·         Destructor must be a public member.    
·         The destructor does not take any argument which means that destructors cannot be overloaded.
·         No return type is specified for destructors.
The example below that the destructor has been invoked implicitly by the compiler.

#include<iostream>
using namespace std;
int count=0;
class alpha
{
                public:
                                alpha()         //constructor
                                {
                                               
                                                count++;
                                                cout<<"\nNo. of Object Created"<<count;
                                }
                                ~alpha()      //destructor
                                {
                                                cout<<"\n No. of Object Destroyed"<<count;
                                                count--;
                                }
                                };
                                main()       // enter to main()
                                {
                                                cout<<"\n\n Enter Main\n";
                                                alpha A1, A2, A3, A4;
                               
                                                cout<<"\n\n Enter Block 1\n";
                                                alpha A5;

                                                cout<<"\n\n Enter Block 2\n";
                                                alpha A6;
                                                cout<<"\n\n Re-Enter Main\n";
                                }              // end of the main()



OUTPUT HERE BELOW…



Conclusion: -I hope helpful for all of you here i am discussing about Constructor and Destructor is class type parameter.

Thanks for Reading… :) In Advance

No comments:

Post a Comment

Please Comment Your Valuable Feedback....

You Might Also Like

Developing Data-Centric Windows Applications using Java

Developing Data-Centric Windows Applications using Java Introduction The Core Java Programming and JDBC course provides an introd...

Unlimited Reseller Hosting