First is that, why is const needed before char? or why is it there?. Also, why is it declaring as a pointer?
I'll start by answering your last question first. This is declared as a pointer so the constructor can accept an array of characters. The const
is there to indicate that the characters being pointed to are not modified inside this bozo
constructor. This is important because your example usage can pass in C-style string literals which typically reside in read-only memory portion of your program. Any attempts to modify such a string literal is undefined behavior.
Second, is there any difference between the "primary form" and the "short form?"
The first form is creating a temporary Bozo
object on the right-hand side and that object is used to initialize bozetta
on the left-hand side. Now you might think that an extra copy happens with this form but that isn't the case. The C++ standard is worded in such a way so that it permits the compiler to skip this unnecessary extra copy during construction by eliding. So in practice, you'll find that on all modern C++ compilers you try this on, bozetta
will be constructed using the prototype you showed above -- no extra copying happens.
The second form explicitly constructs a Bozo
object using a Bozo
constructor that can accept two string literals as parameters.
These two forms have the same behavior assuming that constructor isn't declared explicit
.
I thought char can only contain a single alphabet, and it's not a char array.
That is correct, a char
can only hold one byte worth of information. C and C++ doesn't have an actual native string type, not like the type you're use to like in other languages. So a "string" is really just a bunch of chars
laid out in a contingent block of memory. Your Bozo
constructor above can work with this block by taking a pointer to where that block starts as input.
Could I do this with string instead?
Yes you can and that is actually the preferred way you should do this by using std::string
. The constructor declaration would look like this:
Bozo(std::string fname, std::string lname);
// or to avoid potential copying of long strings
Bozo(const std::string &fname, const std::string &lname);