Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with operator=

Status
Not open for further replies.

apkohn

Technical User
Nov 27, 2000
62
AU
I am writing my first bit of object code in C++, and am having a bit of trouble with operator= overloading.

This is paraphrased from my header file:
Code:
class MyClass
{
public:
   MyClass ( const char* );
   MyClass operator= ( const char* );
...
}

and from the cpp file:
Code:
MyClass :: MyClass ( const char* rhs )
{
   \\ do something and assign it to the new MyClass
}

MyClass MyClass :: operator= ( const char* rhs )
{
   MyClass MC(rhs); \\MC is created as desired
   return MC;
}

Now, the problem is when I try to call say:
Code:
MyClass MC1, MC2;
MC1 = "abcdef";
Within the operator= fucntion, the value is MC is created correctly, however, it just doesn't get assigned to MC1, which is still as initialised in the default constructor.

Please help a newbie to find the problem.
 
You kind of mixed up your code. You expected your got your return object MC to MC1. But it wasn't. If your really want to get the return value, try this:

MC2 = (MC1 = "abcdef");

Now your return object is MC2;

The correct to deal with operator = is like this :

MyClass::eek:perator = (char * rhs)
{
strcpy(_buf,rhs); // say this is operation you needed and _buf is a member of your class
}
you can expect the _buf of your class is initialized.
 
First of all:

your code

MyClass MC(rhs); \\MC is created as desired
return MC;


does nothing because you create an object on the stack the you expect to return it outside of the function. But at the end of every function the function stack is emptied.

you should copy all the members
and then
return *this;

NOTE: I have seen that you haven't also written a default constructor. You will have to write it, becvause you have written the copy constructor and therefore a default constructor cannot be provided.

HTH, s-)

Blessed is he who in the name of justice and goodwill, sheperds the weak through the valley of darkness...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top