Reputation: 68847
I have a class where I use this
to initialize a void*
pointer. But the problem is, when I pass an instance of that class by value, the pointer will not change to the new address on the stack. So, I thought to override the copy constructor to reassign the pointer with the new address of this
. But I need variables to call the super-class constructor, which I normally get by constructor-parameters, but I don't have them in my copy constructor...
I hope I explained well...
So the question is: can I keep the procedure of the default copy-constructor, where I add the part of reassigning the pointer? Or are there better alternatives?
Thanks
Here is a some code:
class GetsCopiedByValue : public SuperClass
{
GetsCopiedByValue(Type1 *t1, Type2 *t2, float var1, /* A lot of other things I need */) :
SuperClass(t1, t2), var1(var1)
{
t1->set_GetsCopiedByValue_Address(this); // ***
}
}
Somewhere else:
{
GetsCopiedByValue instance (t1, t2, 4.64, /* All the other things */);
SomeType *t = new SomeType(instance); // <-- here, it gets copied by value,
} // but the original "instance" goes (here) out of scope and the address
// I assigned (***) is not longer valid, so I have to
// reassign the address to the new address, after copying it.
Upvotes: 2
Views: 411
Reputation: 13421
You will have to store off the parameters when you first construct an object (probably in the superclass since that's what's using them) and then use them again on copy construction i.e. read them back out from the object you are copying from.
Edit
Better still, do as @Konrad Rudoplh suggests and define and use a copy constructor for the base class too.
Upvotes: 0
Reputation: 545568
Not sure if this helps, but you can actually call the superclass copy constructor in your copy constructor:
GetsCopiedByValue(GetsCopiedByValue const& other) :
SuperClass(other), var1(other.var1)
{
t1->set_GetsCopiedByValue_Address(this);
}
But I think that even if you omit this base-class constructor call, C++ will insert it for you.
Upvotes: 2