C/C++ Using Const Object & Variables in C++ Functions

AI Thread Summary
The discussion focuses on using `const Object &` in C++ functions, emphasizing that it allows for call-by-reference without copying the object, enabling direct access to its members. It clarifies that while the syntax differs between using pointers and references, the compiled output is similar, as both methods ultimately reference the same object in memory. A user encounters issues with an array not reflecting changes after passing it to a function, which is attributed to reassigning the pointer within the function rather than modifying the original array. The conversation also suggests that using `std::vector` is a more efficient approach for dynamic arrays compared to manual memory management. Overall, understanding memory semantics and proper usage of references and pointers is crucial for effective C++ programming.
rootX
Messages
478
Reaction score
4
Code:
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 &?
 
Technology news on Phys.org
& 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.
 
rootX said:
Code:
void do_something( const Object & );
And, also what does this mean const Object &?
It uses the address of Object, as if Object was a pointer, but uses a non pointer method of referencing it.
how I can use the object?
As if it wasn't a pointer:

Object.element

Code:
// 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:
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:
#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;
}
 
Jeff Reid said:
Code:
// if the prototype is:
void do_something( const Object *pObject )
// usage is
    pObject->element

// if the prototype is:
void do_something( const Object &rObject[/color])
// usage is
    rObject[/color].element
I've corrected your syntax
 
rootX said:
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.
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?
 
Hurkyl said:
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 you opted not to communicate the address of the new array back to the caller, since you passed that address by value. (Nor did you opt to deallocate the array you discarded)


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 .. ?


Incidentally, is there any particular reason you're 'rolling your own' dynamic array, rather than using the standard std::vector class?

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];
 
rootX said:
So, if I pass array address,
I should not change the address in the method
Or you could pass the address by reference... or you could return the address...

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)
(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?
 
Hurkyl said:
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.

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..
 
  • #10
Hurkyl said:
I've corrected your syntax
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.
 
  • #11
Jeff Reid said:
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.

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
 
  • #12
rootX said:
I am not using vector because I want to stick with basic elements for now for learning purposes.
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.
 
  • #13
KTC said:
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.
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++.
 
Back
Top