Need Help Reg : Overloading assignment Operator,Coppy constructor
Posted by: sarat kuchan
Date: January 05, 2006 08:09AM

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);


}

Options: ReplyQuote


Subject
Views
Written By
Posted
Need Help Reg : Overloading assignment Operator,Coppy constructor
921
January 05, 2006 08:09AM
680
January 06, 2006 08:46AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.