This is kind of basic but I can’t seem to get a hold on this one. Reference here
Are void *p and const void *p sufficiently different? Why would a function use const void * instead of void *?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The reason to use
void*at all (whetherconstor not) is the kind of genericity it provides. It’s like a base class: All pointers arevoid*and can implicitly cast into it, but casts fromvoid*to typed pointers have to be done explicitly and manually.Usually, C++ has better ways to offer to do this (namely OO and templates), so it doesn’t make much sense to use
void*at all, except when you’re interfacing C. However, if you use it, thenconstoffers just what it offers elsewhere: you need an (additional)const_castto be able to change the object referred to, so you are less likely to change it accidentally.Of course, this relies on you not employing C-style casts, but explicit C++ casts. The cast from
void*to anyT*requires astatic_cast, and this doesn’t allow removing ofconst. So you can castconst void*toconst char*usingstatic_cast, but not tochar*. This would need an additionalconst_cast.