Wednesday, April 13, 2011

C++: Deep Copy

#include<iostream>
using namespace std;

class MyStr
{
        char *str;
        public:

        // Constructor
        MyStr(char *_s="")
        {
                if(_s)
                {
                        str = new char[strlen(_s)];
                        strcpy(str,_s);
                }

        }
        //Copy COnstructor
        MyStr(const MyStr & _rhs)
        {
                str = new char[strlen(_rhs.str)];
                strcpy(str,_rhs.str);
        }
        //Assignment Operator
        MyStr& operator=(const MyStr& _rhs)
        {
                //Check for self-assignment
                if(this == &_rhs)
                        return *this;
                // Deallocate memory if it is holding.
                delete [] str;
                //Allocate memory and copy the content
                if(_rhs.str)
                {
                        str = new char[strlen(_rhs.str)];
                        strcpy(str,_rhs.str);
                }
                else
                        str = 0;

                return *this;
        }
        //Destructor
        ~MyStr()
        {
                delete[] str;
                str=0;
        }
        char * getStr()
        {
                return str;

        }

};


int main()
{
        using namespace std;
        MyStr s("Dhananjay Kuamr"),s3;
        {
        s= s;
        }
        cout<<"THe out of s is after =:- "<<s.getStr() <<endl;
        s3 = s;
        cout<<"THe out of s3 is after =:- "<<s3.getStr() <<endl;

}

No comments:

Post a Comment