Tuesday, January 5, 2016

COPY CONSTRUCTOR AND DYNAMIC CONSTRUCTOR

Copy Constructor
    The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to:
  • Initialize one object from another of the same type.
  • Copy an object to pass it as an argument to a function.
  • Copy an object to return it from a function.
EXAMPLE

#include<iostream>
using namespace std;
class Point
{
private:
    int x, y;
public:
    Point(int x1, int y1) 
{ 
x = x1; 
y = y1; 
}
    // Copy constructor
    Point(const Point &p2) 
{
x = p2.x; 
y = p2.y; 
}
    int getX()            
{  
return x;  
}

    int getY()           
{  
return y; 
}
};
int main()
{
    Point p1(10, 15); // Normal constructor is called here
    Point p2 = p1; // Copy constructor is called here
    // Let us access values assigned by constructors
    cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
    cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
    return 0;
}

OUTPUT:
p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15 
Dynamic Constructor

     Dynamic constructor is used to allocate the memory to the objects at the run time.Memory is allocated at run time with the help of 'new' operator. By using this constructor, we can dynamically initialize the objects.

Example:


# include <iostream.h>
# include <conio.h>
# include <string.h>
class str
{
    char *name;
    int len;
    public:
        str()
        {
            len=0;
            name=newchar[len+1];
        }
        str(char *s)
        {
            len=strlen(s);
            name=newchar[len+1];
            strcpy(name,s);
        }
        void show()
        {
            cout<<"NAME IS:->"<<name<<endl;
        }
        void join(str &a,str &b);
};

void str::join(str &a,str &b)
{
    len=a.len+b.len;
    delete new;
    name=newchar[len+1];
    strcpy(name,a.name);
    strcat(name,b.name);
};

main()
{
    clrscr();
    char *first="OBJECT";
    str n1(first),n2("ORIENTED"),n3("PROGRAMMING"),n4,n5;

    n4.join(n1,n2);
    n5.join(n4,n3);
    n1.show();
    n2.show();
    n3.show();
    n4.show();
    n5.show();
}
OUTPUT:
NAME IS:-> OBJECT
NAME IS:-> ORIENTED
NAME IS:-> PROGRAMMING
NAME IS:-> OBJECT ORIENTED
NAME IS:-> OBJECT ORIENTED
Destructor:
 A destructor as the name implies is used to destroy the objects that have been created by a constructors. Like a constructor, the destructor is a member function whose name is the same as the class name bur is preceded by a tilde. for example, the destructor for the class sample can be defined as shown below:
       ~sample(){     }

No comments:

Post a Comment