Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between void pointers in C and C++

Tags:

c++

Why the following is wrong 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 the casting,as p now contains address of char pointer and s is also char pointer?

like image 818
Naveen Avatar asked Nov 29 '22 02:11

Naveen


1 Answers

That's valid C, but not C++; they are two different languages, even if they do have many features in common.

In C++, there is no implicit conversion from void* to a typed pointer, so you need a cast. You should prefer a C++ cast, since they restrict which conversions are allowed and so help to prevent mistakes:

s = static_cast<char*>(p);

Better still, you should use polymorphic techniques (such as abstract base classes or templates) to avoid the need to use untyped pointers in the first place; but that's rather beyond the scope of this question.

like image 107
Mike Seymour Avatar answered Dec 05 '22 09:12

Mike Seymour