Why does the write method take a character pointer to the object one wishes to write?

A

AMT2K5

Would it not be more efficient to take in a void pointer?

int number = 30;
fout.write((char *)(&number), sizeof(number));
 
B

Bob Hairgrove

Would it not be more efficient to take in a void pointer?

int number = 30;
fout.write((char *)(&number), sizeof(number));

No. Why do you think it would be more efficient?
 
B

Bob Hairgrove

What purpose does it serve to cast as a character pointer?

You are telling fout to write an int as binary data, so you must cast
the address of your number to a char* and give the size so that the
stream knows how many bytes (i.e. char's) to write.

The problem with void* is that void is not a type. With char*, you
know that you are dealing with a type which is exactly one byte large.
And a pointer to an object can be implicitly converted to void*, so
using char* is more type-safe. That is one of the major advantages of
C++ over C, for example.

But you still didn't say why you think void* would be more efficient?
The cast doesn't cost any processor cycles, nor does it take up any
extra memory.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top