When you typecast a variable, a temporary variable is created, right? Is the temporary variable constant (const) ?
My book says this:
That sounds logical, but I'm having trouble compiling this:Actual arguments must be type-compatible with the formal arguments, without the use of a typecast. This is required because a typecast generates a temporary variable and that temporary variable would become the actual argument. Then changes to the formal parameter in the invoked function would change the temporary variable (instead of the original), leading to hard-to-find bugs.
Reaction of the compiler:Code:#include <iostream> using namespace std; class Person { public: Person(const string &n): name(n) { } string name; }; class Student: public Person { public: Student(const string &n): Person(n) { } }; void changeName(Person &p, const string &n) { p.name = n; } int main() { Student s("Fred"); changeName((Person)s, "Mark"); cout << "Name: " << s.name << endl; return EXIT_SUCCESS; }
The code doesn't make sense, I know, but I just wanted to create a temporary variable. Why won't this compile? Is the result of the typecast constant?../main.cpp: In function `int main()':
../main.cpp:24: error: invalid initialization of non-const reference of type 'Person&' from a temporary of type 'Person'
../main.cpp:18: error: in passing argument 1 of `void changeName(Person&, const std:string&)'
mingw32-make.exe: *** [main.o] Error 1



LinkBack URL
About LinkBacks



Want to add some 