Saturday, April 16, 2011

C++: Operator Overloading

#include<iostream>

using namespace std;

class A
{
        int a;
        public:
                A(int x=0):a(x){
                        cout<<"in Cons"<<endl;
                }
                friend A operator+(const A& _a1, const A& _a2);
                friend ostream& operator<<(ostream &out, const A& _a);
                int getData()
                {
                        return a;

                }
};

A operator+(const A& _a1, const A& _a2)
{
        cout<<"Inside operator+"<<endl;

        return  A(_a1.a + _a2.a);

}
ostream& operator<<(ostream & o, const A& _a)
{
        o << _a.a;
        return o;

}

int main()
{
        A x1(2), x2(3);
        A x3 = x1  + x2;
        cout << x3 <<",  "<<x1<<endl;

}

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;

}