Thread: Typecasting, temporary variables and call by (constant) reference

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    3

    Typecasting, temporary variables and call by (constant) reference

    When you typecast a variable, a temporary variable is created, right? Is the temporary variable constant (const) ?

    My book says 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.
    That sounds logical, but I'm having trouble compiling this:

    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;
    }
    Reaction of the compiler:
    ../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
    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?

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> Is the temporary variable constant

    Basically, yes. You cannot pass a temporary to a function that takes a non-const reference, because the temporary will be changed (which has no real effects). In the example above, if you remove the cast, it will compile correctly because Student is type-compatible with Person (you can pass a Student to a function taking a Person reference without a cast because Student derives from Person).

  3. #3
    Registered User
    Join Date
    Jan 2006
    Posts
    63
    When you type cast, you temporarily change the data type, to be compatible with the same data type as you are assigning to, or doing whatever you are doing to. At least I think so, it may be wrong.

    Code:
    int main(){
    
    	int int_datatype = 20;
    	char* char_datatype;
    
    	char_datatype = int_datatype;
    
    	return 0;
    }
    That code gives this error.

    error C2440: '=' : cannot convert from 'int' to 'char *'
    Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
    This code shows typecasting.

    Code:
    int main(){
    
    	int int_datatype = 20;
    	char* char_datatype;
    
    	char_datatype = (char*)int_datatype;
    
    	return 0;
    }

  4. #4
    semi-colon generator ChaosEngine's Avatar
    Join Date
    Sep 2005
    Location
    Chch, NZ
    Posts
    597
    just as an aside you should prefer the C++ style casts (static_cast, reinterpret_cast, etc) to c casts. The problem with c-style casts is that they don't stand out in the code. It's easy to read a page of code and miss a casting bug with c-style casts. C++ casts are ugly and standout from the code.

    according to bjarne
    An ugly operation should have an ugly syntactic form.
    "I saw a sign that said 'Drink Canada Dry', so I started"
    -- Brendan Behan

    Free Compiler: Visual C++ 2005 Express
    If you program in C++, you need Boost. You should also know how to use the Standard Library (STL). Want to make games? After reading this, I don't like WxWidgets anymore. Want to add some scripting to your App?

  5. #5
    Registered User
    Join Date
    Jan 2006
    Posts
    63
    Quote Originally Posted by ChaosEngine
    just as an aside you should prefer the C++ style casts (static_cast, reinterpret_cast, etc) to c casts. The problem with c-style casts is that they don't stand out in the code. It's easy to read a page of code and miss a casting bug with c-style casts. C++ casts are ugly and standout from the code.

    according to bjarne
    An ugly operation should have an ugly syntactic form.
    You know considering this is the C++ programming section I should have said that, but to be honest I have never used C++ typecasts. So this is a first for me

    Thanks ChaosEngine.

  6. #6
    Registered User
    Join Date
    Jan 2006
    Posts
    3
    So the compiler is preventing me from doing something stupid (i.e. modifying a temporary variable instead of the original)?

    That's a first. I thought C++ was very permissive by nature.

  7. #7
    !anExpert
    Join Date
    Mar 2005
    Location
    pa
    Posts
    155
    > I thought C++ was very permissive by nature.

    just the opposite actually..

  8. #8
    Registered User
    Join Date
    Jan 2006
    Posts
    3
    Still... it makes more sense that a compiler would give a warning in this case, instead of an error.

  9. #9
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Maybe, but there just might be more complicated reasons to not allow that.

    Besides, there is no reason to do it, so why allow it?

  10. #10
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    I think this is what your book is trying to explain:
    Code:
    #include <iostream>
    using namespace std;
    
    void changeIt(int& num)
    {
    	--num;
    }
    
    int main ()
    {
    
    	int n = 10;
    	changeIt(n);
    	cout<<n<<endl; //As expected the function changes n.
    
    
    	double d = 3.5;
    	changeIt(static_cast<int>(d));
    	cout<<d<<endl; //Does the function change d?
    
    	
    	return 0;
    }
    Your book says that the typecast of d creates a temporary variable which is passed to the function. The function then ends up changing the temporary variable, so d is unchanged by the function.

    However, the example won't even compile in VC++6. I get an error on the line that calls print():

    error C2664: 'print' : cannot convert parameter 1 from 'int' to 'int &'
    A reference that is not to 'const' cannot be bound to a non-lvalue
    So, this warning rings hollow:
    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.
    I don't know why the compiler won't let you change a temporary variable--maybe that's the nature of a temporary variable.

    Is the temporary variable constant (const) ?
    It appears so since this compiles:
    Code:
    #include <iostream>
    using namespace std;
    
    void changeIt(const int& num)
    {
    	//but now you can't change the parameter variable
           //inside the function
    }
    
    int main ()
    {
    
    	int n = 10;
    	changeIt(n);
    	cout<<n<<endl; 
    
    
    	double d = 3.5;
    	changeIt(static_cast<int>(d));
    	cout<<d<<endl; 
    
    	
    	return 0;
    }
    Last edited by 7stud; 01-29-2006 at 08:01 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Call by reference question
    By badtwistofate in forum C Programming
    Replies: 4
    Last Post: 03-24-2009, 02:40 PM
  2. How to get RSSI value, send to sensor, sensor receive package, repackage it?
    By techissue2008 in forum Networking/Device Communication
    Replies: 1
    Last Post: 03-04-2009, 10:13 AM
  3. Using call by reference in this program
    By BurleMD in forum C Programming
    Replies: 3
    Last Post: 10-28-2006, 12:23 PM
  4. Variable Call via Another Variable's Content
    By E-Rac in forum C++ Programming
    Replies: 2
    Last Post: 01-18-2005, 01:51 PM