Is the following solution correct?

Hello,

I'm learning C++ from the book "C++ Primer", 5th edition.

In chapter 4, exercise asks the following:

Rewrite each of the following old-style casts to use a named
cast:

int i; double d; const string *ps; char *pc; void
*pv;

(a) pv = (void*)ps;
(b) i = int(*pc);
(c) pv = &d;
(d) pc = (char*) pv;


Is the following solution correct?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <string>
using std::string;

int main()
{
	int i; double d; const string *ps;
	char *pc; void *pv;

	pv = const_cast<string*>(ps);
	i = static_cast<int>(*pc);
	pv = static_cast<void*>(&d);
	pc = reinterpret_cast<char*>(pv);

	return 0;
}
Yes, I agree with you.

And, pv = static_cast<void*>(const_cast<string*>(ps)); more better.
Topic archived. No new replies allowed.