Lecture overview -- Keyboard shortcut: 'u'  Previous page: References - Examples -- Keyboard shortcut: 'p'  Next page: References versus Pointers -- Keyboard shortcut: 'n'  Lecture notes - all slides and notes together  slide -- Keyboard shortcut: 't'  Help page about these notes  Alphabetic index  Course home  Lecture 2 - Page 18 : 42
Notes about C++
Basic facilities
Constant References

A constant reference is really a reference to a constant

"An initializer for const T&   does not need to be an lvalue, or even of type T."

  • The C++ Programming Language: Page 98, 146, 148, 283
 

  const T &var = expression;

Const ref scheme.

  • Initialization of var - a reference to T

    • Implicit conversion from the type of expression to T is performed

    • The result is placed in a temporary variable of type T

    • var is bound to the tempory variable - which cannot be mutated

It would be undesirable and misleading to be able to modify var, because it is just a temporary variable.

y:/Kurt/Files/Advanced-programming-cpp/cpp/kn/references/const-ref-t-1.ccThe initialization of var in a real, but simple context.


y:/Kurt/Files/Advanced-programming-cpp/cpp/kn/references/const-ref-t-3.ccA similar program that initializes a user defined struct via a 'functional casting' constructor.


y:/Kurt/Files/Advanced-programming-cpp/cpp/kn/references/ref-div.ccAn envelope around the stdlib div function that returns a struct of quotient and remainder.


Go to exerciseWays of returning results from the div function
y:/Kurt/Files/Advanced-programming-cpp/cpp/kn/references/const-ref-t-2.ccA similar setup - illustrates that it is not good to return a reference to a deallocated local variable.