Originally Posted by
SAP_7
but what is the difference b/w void and (void *).
They are different types:
- "The void type has an empty set of values. The void type is an incomplete type that cannot be completed. It is used as the return type for functions that do not return a value." (from C++11 Clause 3.9.1 Paragraph 9)
- The void* type is the type "pointer to void". It is used to generically point to objects (which doesn't mean objects of class type only, hence a pointer to int can be converted to a pointer to void), with caveats such as that a pointer of this type cannot be dereferenced.
Originally Posted by
SAP_7
I mean to ask you like in the code i have posted, i would like to check is this void pointer before casting using this line pack *p3=static_cast<pack*>(p2);.
please see my code which i posted at first
Bearing in mind what I wrote above, it is obvious that your question does not make sense: the type of p2 is already known from a visual inspection of the code to be a pointer to void (or "void pointer", if you prefer), since it was declared to be a pointer to void.
Maybe you are asking how to check if p2 is not a null pointer, but it is certainly not a null pointer because it is initialised from p1. p1 cannot be a null pointer since it is initialised with the result of new pack, which would throw std::bad_alloc on allocation failure (or possibly some other exception, e.g., on constructor failure, though that is not applicable here). If you did want to check if p2 is not a null pointer, using it in a boolean context would do as what swgh demonstrated in post #2, though personally I would rather write:
Code:
if (p2)
{
// p2 is not a null pointer
}
if (!p2)
{
// p2 is a null pointer
}
Also, note that if you are compiling with respect to C++11 or later, you should use nullptr instead of NULL.
Note that you do not need the cast here:
Code:
void *p2=(void *)p1;
Any pointer to object type is implicitly convertible to pointer to void, so this would suffice:
However, the cast here is required, and it is good to see that you used the most appropriate cast:
Code:
pack *p3=static_cast<pack*>(p2);
Even though the OS is likely to reclaim the memory allocated after the process terminates, it is still good practice to match new with delete.