I am reading C++ Primer and I found something really weird and hard to understand:
Record lookup(Account&); //Record and Account are two unrelated class
Record lookup(const Account&);
So these two functions both accept non-const object (match non-const parameter function first), but only the second function can accept const object.
And from next section (const_cast and overloading) I have these code:
const string &shorterString(const string &s1, const string &s2){
return s1.size() < s2.size() ? s1 : s2;
}
string &shorterString(string &s1, string &s2){
auto &r = shorterString(const_cast<const string&>(s1),
const_cast<const string&>(s2));
return const_cast<string &>)(r);
}
what on earth does const_cast<const string&>(s1)
mean?
As I was told:
A reference is the object, just with another name. It is neither a pointer to the object, nor a copy of the object. It is the object.
So I pass a string object to initialize a reference s1
, so s1
itself is a string object, then how can it cast a string
to const string&
and then to match the other function?
How should understand the function call ?
shorterString(const_cast<const string&>(s1),const_cast<const string&>(s2));
Is it using a reference to initialize a reference? But since a reference is an object itself, than I am using the object which s1 refers to initialize and its a string. so again, const_cast<const string&)(s1)
, string
to const string&
?
From my point of view, if you have a string object, then you can only match the non-const reference parameter function, and there is no something like:
string s1 = "abc";
string s2 = "efg";
shorterString(const(s1), const(s2)); //no such top-level const cast
PS: when it comes to non-const and const pointer parameter, it's understandable.
In case of tedious question, I uploaded screenshots of related paragraph from the book: