Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Passing by Reference in C++

KhethoKhetho Member Posts: 2
When you are passing a variable by reference into a function say as follows

TheFunction (const Int &ThisObject);

In the calling function the integer variable to be passed is not a constant but the function prototype declares the parameter ThisObject as a constant reference. If I pass in the non constant integer ThisInteger to from the calling function. As passage is by reference will the const keyword in the prototype affect the variable ThisIntegere to the extent that you can not alter its value after TheFunction returns

Comments

  • PeterTheMasterPeterTheMaster Member Posts: 636
    absurd nonsense.
  • stoberstober Member Posts: 9,765 ✭✭✭
    : When you are passing a variable by reference into a function say as follows
    :
    : TheFunction (const Int &ThisObject);
    :
    : In the calling function the integer variable to be passed is not a constant but the function prototype declares the parameter ThisObject as a constant reference. If I pass in the non constant integer ThisInteger to from the calling function. As passage is by reference will the const keyword in the prototype affect the variable ThisIntegere to the extent that you can not alter its value after TheFunction returns
    :


    I think you are misusing the const keyword. In this instance, why pass an integer by reference but indicate its value cannot be changed? One of the purposes of references is to allow the called function can change its value. If you don't want it changed, simply pass it by value.


  • PeterTheMasterPeterTheMaster Member Posts: 636

    : I think you are misusing the const keyword. In this instance, why pass an integer by reference but indicate its value cannot be changed? One of the purposes of references is to allow the called function can change its value. If you don't want it changed, simply pass it by value.
    :

    this is only true for simple small data types like int, since int is as long as a pointer, its as fast to copy an int as passing a pointer, and then you dont have to do the dereferencing. but for string or any selfmade classes, const ref is the way to go.

  • Chris BrownChris Brown USAMember Posts: 4,496 ✭✭

    [ http://forcoder.org ] free ebooks and video tutorials about ( Visual Basic .NET, JavaScript, Java, Delphi, C++, MATLAB, Perl, C, PL/SQL, Swift, Visual Basic, R, Objective-C, Ruby, Scratch, Go, Python, C#, PHP, Assembly Scala, Clojure, Dart, FoxPro, Fortran, ABAP, Crystal, Awk, VBScript, F#, Julia, Rust, Bash, Apex, Alice, Ada, Prolog, Transact-SQL, Scheme, LabVIEW, Lua, Hack, SAS, D, COBOL, ML, Kotlin, Lisp, Erlang, Logo ) ____

Sign In or Register to comment.