I’m going through the full tutorial at cplusplus.com, coding and compiling each example manually. Regularly, I stumble upon something that leaves me perplexed.
I am currently learning this section: http://www.cplusplus.com/doc/tutorial/structures/ . There are some subtleties that could easily be overlooked by only reading the tutorial. The advantage of typing everything by hand is that such details do stand out.
In the above page, there are two sample programs. One has this line:
stringstream(mystr) >> yours.year;
The other one has this line:
(stringstream) mystr >> pmovie->year;
What I don’t understand is the difference (if any) between type (myVar) = x; and (type) myVar = x;.
I am not doing the whole tutorial in sequential order. I checked but didn’t find this addressed anywhere, though I may have missed it.
- Is there a difference?
- Is there a preferred way to do it one way rather than the other?
There is no difference between
type(x)and(type)x. These two are completely equivalent. Most people prefertype(x)for classes and(type)xfor non-class types, but that’s purely up to one’s own choice. Both call constructors for classes with one argumentx.The preferred way for classes is
type(x), because this allows passing more than one argument to the constructor, as intype(x, y). Trying to apply the other form,(type)x, ywill not work: It castsx, and then applies the comma operator and evalutesyin isolation. Parentheses like(type)(x, y)do not help: This will evaluatexandyin isolation using the comma operator and then castytotype.For non-class types, such a cast is often too powerful. C++ has
static_cast<type>(x)for roughly doing the reverse of an implicit conversion (such as casting base classes to derived classes and castingvoid*to another pointer), which often is what fits in. See When should static_cast, dynamic_cast and reinterpret_cast be used?.stringstreamis not a function, though. Doingfunction(x)will call it the function, but doing(function)xis illegal, beause there are two expressions next to each other, with no operator in between.For those who don’t believe this answer, and downvote it on gut feeling, please consult the Standard at
5.2.3/1