Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ function variables

  1. Sep 9, 2008 #1
    Code (Text):
    void do_something( const Object & );
    How I can refer to to the passed in variables when I implement these functions.

    let's say I am implementing as following:

    template<typename Object>
    myclassname::do_something(const Object &)
    {
    //how I can use the object
    }

    And, also what does this mean const Object &?
     
  2. jcsd
  3. Sep 9, 2008 #2

    malawi_glenn

    User Avatar
    Science Advisor
    Homework Helper

    & means that you do a "call-by-reference"

    This means that you only use the value of the parameter, and not the parameter itself.

    If your Objects is a member of a class, with functions, you can access by doing:

    void template<typename Object>
    myclassname::do_something(const Object &)
    {double dd;
    dd = 5*rand();
    Object.Increase(dd);
    }

    You might want to pick up an introductory book on C++ programming.
     
  4. Sep 9, 2008 #3

    rcgldr

    User Avatar
    Homework Helper

    It uses the address of Object, as if Object was a pointer, but uses a non pointer method of referencing it.
    As if it wasn't a pointer:

    Object.element

    Code (Text):

    // if the prototype is:
    void do_something( const Object *pObject )
    // usage is
        pObject->element

    // if the prototype is:
    void do_something( const Object &)
    // usage is
        Object.element
     
    Although the source code is different in the two examples above, the compiled executable will essentially be the same. In the second case "Object &", the compiler creates a pointer to Object, and then dereferences it when Object is used, allowing the syntax Object.element to be used instead of pObject->element.

    Here's another thread that covers the usage of & in C++:

    https://www.physicsforums.com/showthread.php?t=246549
     
    Last edited: Sep 9, 2008
  5. Sep 12, 2008 #4
    Thanks for the help. I have understood that part but I am stuck again. I have read the introductory tutorials but I just can't remember pointers ....

    Here's my another problem:
    There's a method that takes int array and I pass it by reference using pointer.
    It doesn't change initial array so that means it is not taking it by reference.
    I don't know what's wrong.

    Code (Text):
    #include <iostream>
    #include <cmath>
    using namespace std;

    //stores binary representation of B in the array binary
    void convert_binary(int N, [B]int *binary = new int[0][/B], int *total=0, int counter = -1)
    {
        if (N > 0)
        {
            //begining
            if (counter == -1)
            {
                //declares parameter
                counter = ceil(log((double)N)/log((double)2));
                binary = new int[counter];
                *total =counter;
                for(int i=0; i<*total;i++)
                    binary[i] = 0;
            }

            //stores the digit
            binary[counter] = N%2;
            cout<<"Counter: "<<counter<<" N%2: "<<N%2<<" binary["<<counter<<"]: "<<binary[counter]<<endl;
            //updates parameters
            counter--;
            N = N/2;
            convert_binary(N,binary,total,counter);
        }
        else
        {
            cout<<"ENDING ... "<<endl;
            for(int i=0; i<*total;i++)
                cout<<binary[i]<< "  ";
            cout <<endl<<"ENDED "<<endl; [B]// this provides correct output 0 1 0 1 0 1 .. I am inside method[/B]
        }
    }

    int main()
    {
        int * binary = new int[10];
        int *total = new int(10);
        convert_binary(21,binary,total);

        for(int i=0; i<*total;i++)
            cout<<binary[i]<< "  ";  [B]//no changes to the array![/B]
        cout<<endl<<"FINISH"<<endl;
        return 0;
    }
     
  6. Sep 12, 2008 #5

    Hurkyl

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    I've corrected your syntax
     
  7. Sep 12, 2008 #6

    Hurkyl

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    It does take the array by reference. It's just that one of the very first things you did was to change the reference to point to some other array:
    binary = new int[counter];​
    And the pointer binary was passed by value.... (and you forgot to deallocate the original array that you were discarding)

    Incidentally, is there any particular reason you're 'rolling your own' dynamic array, rather than using the standard std::vector class?
     
  8. Sep 12, 2008 #7

    So, if I pass array address,
    I should not change the address in the method
    and, deallocate means "delete binary;" which should be near the main method end .. ?


    It's dynamic? I thought I couldn't change the elements # (I am from Java + C#), and if I change elements #(not defined in this array: say array was 5 but I am modifying the 6th) then I might be changing values of other variables that are stored in that address.

    I am not using vector because I want to stick with basic elements for now for learning purposes.

    Thanks, I commented that line out and it works now: //binary = new int[counter];
     
  9. Sep 12, 2008 #8

    Hurkyl

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Or you could pass the address by reference... or you could return the address....

    (Builtin) arrays are not dynamic, but your usage of them can be -- e.g. by reallocating the array whenever it's current form isn't suitable for your purposes, which you were doing to a (very) limited extent.


    By the way, what is your intended use of this function? The way you called your function, and your comments above, make it sound like you want to demand the caller to have already allocated space to store the result (and you are trusting him to get it right!). However, the way you wrote your function makes it look like you wanted it to handle the job of correctly allocating space. These designs seem to conflict with one another.


    Oh, and your calculation of the # of digits is wrong; what result do you get if, say, N = 2?
     
  10. Sep 12, 2008 #9
    It converts 10 digit numbers to binary using recursion using
    N = (int) N/2 + N%2
    (int) N/2 = ...

    and I place 0s and 1s in the int array using counter parameter. And I have total by reference so that I return the total # of elements stored in the array.

    I have counter just that I know where to insert the 0/1 for current iteration/step.. and that's why I just want user to have binary and total in main so that I use them by reference in my method.

    It returns incorrect values but I only wanted to practice the concepts of passing by reference etc.. I would have used for/while to get more elegant solution..
     
  11. Sep 12, 2008 #10

    rcgldr

    User Avatar
    Homework Helper

    Thanks it was too late to edit it, I posted a correction, but the forum got stuck and I didn't follow up on this.
     
  12. Sep 12, 2008 #11
    It's funny that malawi_glenn also made the same mistake but I just referred to another thread and read my notes again. Concepts seems to be important than the code
     
  13. Sep 13, 2008 #12

    KTC

    User Avatar

    The standard library container like std::vector is part of the basic elements. Using dynamically allocated arrays properly is much more complicated than just using std::vector.
     
  14. Sep 13, 2008 #13

    Hurkyl

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Right. To expand on this....


    Learning C/C++ memory semantics is something worth doing -- but before you jump head-first into it, make sure that's really what you intend to get out of your exercise. While C's limited syntax required the programmer to explicitly manage memory (and other resources), that style of programming is mostly obsolete in C++.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: C++ function variables
  1. C++ function (Replies: 3)

  2. Functions in c (Replies: 1)

  3. C# with C++ functions (Replies: 2)

  4. Random function in C (Replies: 31)

Loading...