Need Help Reg : Overloading assignment Operator,Coppy constructor
Hi Friends,
I am tyring to understand Coppy constructor and assignment opp
I just developed a code snippet ( ofcourse its a bad code coz just for experiment)
in there ( in main function)
when Create and objebt like MyClass M1(6,"sarat");
and another one like MyClass M4() and invoke assignmet opp
like this M4 = M1 ; it wont even compile only
it gives the error saying : "error C2659: '=' : overloaded function as left operand"
but if i create an objevt like this -- MyClass M4(6,"sarat"); // wat ever the values
and invoke the assignment operator like this -- M4 = M1;
then there wont be any error and its complied and excecuted.
I need to know what was the error when i was doing like this MyClass M4(); and M4 = M1
and clear ly i wanna know how does the error message and explanation displyed by VC++ 6 , related to the error
I need explanation for this plz
Here is the code snippet:
#include<stdio.h>
#include<windows.h>
//
class MyClass
{
public:
MyClass();
MyClass(INT strlen , CHAR * str );
MyClass(MyClass const & A);
MyClass& operator= (MyClass const & A);
~MyClass();
private:
INT stringlen;
CHAR *mystring;
};
MyClass::MyClass()
{
}
MyClass::~MyClass()
{
//if( mystring )
// free(mystring);
}
MyClass::MyClass(MyClass const &A)
{
stringlen = strlen( A.mystring );
mystring = new char[ stringlen+1 ];
strcpy( mystring, A.mystring);
}
//assignement operator
MyClass&
MyClass::operator= (MyClass const &A)
{
if ( this != &A )
{
delete [] this->mystring;
this->mystring = new char[strlen(A.mystring)];
strcpy( this->mystring, A.mystring);
}
return *this;
}
MyClass::MyClass( INT strlen1 = 0 , CHAR * str = "" )
{
stringlen = strlen( str );
mystring = (CHAR*) calloc( sizeof( CHAR ), stringlen + 1);
strcpy ( mystring, str );
}
void main()
{
MyClass M1(6,"sarat");
MyClass M2 = M1;
MyClass M3(M2);
MyClass M4(6,"sarat");
M4 = M1;
CHAR *str, *str1 = "sarat";
str = ( CHAR* ) calloc ( sizeof (CHAR), 10);
strcpy( str,"sarat");
str[2]= 's';// shud work
printf("%d %d ",strlen(str),strlen(str1));
//str1[2]= 's'; will not work coz we assigned a constant
printf("%s %s", str, str1);
}