Difference between void pointers in C and C ++

Why the following is not true in C ++ (but valid in C)

void*p; char*s; p=s; s=p; //this is wrong ,should do s=(char*)p; 

Why do I need casting, since p now contains the address of the char pointer, and s also contains the char pointer?

+4
source share
3 answers

The value does not matter the type does. Since p is a pointer to void and a pointer to a a char, you need to discard even if they have the same value. In C, this will be fine, void* is a generic pointer, but this is not true in C ++.

By the way, p does not contain a char pointer, it is a pointer to void and contains a memory address.

+8
source

This is valid C, but not C ++; they are two different languages, even if they have many common features.

In C ++, there is no implicit conversion from void* to a typed pointer, so you need to throw. You should prefer C ++ casting, as they limit which conversions are allowed, and therefore help prevent errors:

 s = static_cast<char*>(p); 

Even better, you should use polymorphic methods (for example, abstract base classes or patterns) to avoid the need to use untyped pointers in the first place; but it is rather beyond the scope of this question.

+16
source

In general, this rule has nothing to do with pointers. You can simply assign values ​​of a certain type to variables of other types, but not always the other way around. A similar situation would be this:

 double d = 0.0; int i = 0; d = i; // Totally OK i = d; // Warning! 

So, something that you need to live with.

0
source

Source: https://habr.com/ru/post/1493185/


All Articles