I have the following code :
void testCopy(){
Balloon* b1=new Balloon(1,5,6,3);
Balloon* b2=new Ballon(2,4,4,2);
cpyBallon(b1,b2);
assert(b1->getCenterx()==5);
cout<<" cpyBalloon() OK!\n";
}
and the code for the cpyBalloon() is
void cpyBalloon(TCE& dest,TCE src){
Balloon* b=(Balloon*) src;
Balloon* d=new Balloon();
*d=*b;
dest=d;
}
where TCE if of type void*.
The problem is that i don’t know how to pass the object b2 which is of type Balloon* as void*&. I keep getting the following error:
..\src\/Domain/BalloonTest.h:68:18: error: invalid initialization of reference of type 'void*& {aka void*&}' from expression of type 'domain::Balloon*'
..\src\/Domain/Balloon.h:102:10: error: in passing argument 1 of 'void domain::delBalloon(void*&)'
I know that b2 is the argument with which I have the problem but I don’t know how what to do to make it work.
As your code states, you have a Balloon class. You’ve dynamically allocated memory for two Balloon instances and called their constructors, filling them in with respective data. Then, you stored the address of each of those objects into proper raw pointers.
This typedef:
is pointless. A reference to a
void*(void*&) is also pointless. Why? Becausevoid*holds only one value – the first byte of a stream of bytes (their count is lost when you interpret anything asvoid*, that’s because count is type-dependent). So, it is already a pointer. You’re not passing an entire stream of bytes, just the address of the first byte. And then you further interpret it in the function as you’d like.But in this case, it’s not necessary to interpret it as such. A reference, when analyzed from a really low level, is just a pointer in disguise and enables us to reap the benefits of pointers safely (without thinking about it too much). There’s more to it, but for now, this is important.
You can either:
void*, then undo the cast in the function (for whatever good that will do).Observe first:
Observe second:
Observe third (dear lord…):
You can also reinterpet_cast to circumvent all compiler help with type checking which is extremely dangerous and if you have to use it, you’re either very wrong or have a really nasty problem (which could stem from your approach being very wrong). Notice the
constness around the source, that’s good practice whenever you want something copied and undamaged.Also note that there is a lot of memory management that arises in these situations, this is just a simple situation.