Assignment between different objects

Hi all.
A have two classes: STowar and CTowar-internal.
The goal is to assign a STowar object to CTowar_internal object like this:
CTowar_interanl twi;
STowar t;
...
//filling t object
...
twi = t; // [1]

Here [1] I want to assign. But the problem is, I can't touch the CTowar_internal class to make a new assignment operator, I can only modify the STowar class.
So, I made in STowar a assignment operator:
CTowar_internal& operator=(STowar& tw)
{
CTowar_internal* ret = new CTowar_internal();
ret->KK = "asdf";
return *ret;
}

But it doesn't work. It compiles properly, but the assignment doesnt work. twi object doesn't contain the "asdf" string. Of course, later i will do in the operator body a lot of staff, now it's only "asdf" assignment for testing.
Is this possible to do this by above operator ?
will not work .
it should be ..

1
2
3
4
5
void  operator=(STowar& tw)
{
   this->KK = tw.KK;
   //ret->KK = "asdf";
}


why iths ret->KK = "asdf"; and also why you pass STowar & tw to the operator when you are not using it .
"...Of course, later i will do in the operator body a lot of staff, now it's only "asdf" assignment for testing..."

Your solution is properly - this->KK = tw.KK. I said, I will do this stuff later because, there a lot of int's,bool's, CString to assign.

Why 'void' ? Now it should work ?
Last edited on
Why 'void' ? Now it should work ?

because you are doing the operation in the object itself , no need to return any thing .
And Yess .. i suppose it should work .
Hi

:-) without seeing your class-structures of both classes , cant say any thing.

First:
1
2
3
4
5
{
CTowar_internal* ret = new CTowar_internal(); //memory leak once the operator returns
ret->KK = "asdf";
return *ret;
}


I don't understand your not having access to the internals, do you mean logically or physically (or you have been instructed not to change the code for that class)?

Does STowar contain a CTowar-internal?
If this is the case why not just add a function, name it whatever you want. Assuming Ctowar-internal has an operator= where Ctowar-internal = Ctowar-internal then:

1
2
3
4
5
//...
STowar war;
Ctowar_internal internal;
//... bla bla...
internal = war.AsInternal();


Where AsInternal is something like...
1
2
3
4
const Ctowar_internal& StoWar::AsInternal()
{
   return this->KK; //Where KK is a Ctowar_internal
}

Last edited on
Topic archived. No new replies allowed.