Reputation: 9648
I'm relatively new to C++, I start by reading C++ Primer 4th edition. It has a section explains about Pointers and Typedefs, start with bellowing code.
typedef string *pstring;
const pstring cstr;
I know that after I define typedef string *pstring;
I can use *pstring
to declare string variable in my code.
*pstring value1; // both of these line are identical,
string value2; // value 1 and value2 are string
The book continue with const pstring cstr1;
and *const string cstr2;
are identical. I don't understand why they're same declaration?
Upvotes: 0
Views: 309
Reputation: 263257
I really hope the book you're quoting isn't as inaccurate as your quotations make it seem. I feel sure that you haven't quoted it accurately. Please go back and compare what's in the book (I don't have a copy) to what you've written.
Given:
typedef string *pstring;
You write that
const pstring cstr1;
and
*const string cstr2;
are identical. In fact, both are invalid.
If you declare something const
, you need to provide an initial value for it. And the syntax of *const string cstr2;
is just wrong.
So here's a correct way to do it:
typedef string *pstring;
const pstring cstr1 = 0; // initialize to 0, a null pointer
string *const cstr2 = 0; // the same
Both cstr1
and cstr2
are const (i.e., read-only) pointers to string.
Note that the const
keyword has to be after the *
, because we want a const pointer to string, not a pointer to const string.
But in any case, declaring a typedef for a pointer type is usually a bad idea. The fact that a type is a pointer type affects almost everything you do with it; making a typedef for it hides that fact.
Upvotes: 2
Reputation: 16081
It's great that you are learning about typedefs, but personally when you see ten thousand of them in your application with millions of lines of code, then.... typedefs lose their luster. They then only serve to obsfucate the real code. I swear some devs whose code I've maintained drank the typedef cool aid and use them for everything!
The only benefit I've seen is to use them to shorten very long typed names. such as long types used with the STL.
Upvotes: 1
Reputation: 19032
They are not identical.
pstring v1; // declares a pointer to string
string v2; // declares an object of type string
string* v3; // this is the same type as v1
Upvotes: 4