Using Const Object & Variables in C++ Functions

Click For Summary

Discussion Overview

The discussion revolves around the use of const objects and pointers in C++ functions, particularly focusing on how to implement functions that take parameters by reference and the implications of doing so. Participants explore concepts related to function prototypes, memory management, and the behavior of arrays in C++.

Discussion Character

  • Technical explanation
  • Conceptual clarification
  • Debate/contested
  • Homework-related

Main Points Raised

  • Some participants inquire about the meaning of "const Object &" and how to use the passed object within a function.
  • Others explain that "&" indicates a call-by-reference, allowing access to the parameter without copying it, and provide examples of using member functions on objects.
  • One participant clarifies that using "const Object &" allows for syntax similar to using a pointer, while another emphasizes that the compiled output is essentially the same as using a pointer.
  • A participant expresses confusion about passing an integer array by reference using a pointer, noting that changes to the array do not reflect outside the function.
  • Responses highlight that the issue arises from changing the pointer to a new array within the function, which does not affect the original array passed by value.
  • Some participants suggest using standard containers like std::vector instead of manually managing dynamic arrays.
  • There are discussions about the intended use of the function, with some participants pointing out potential design conflicts in how memory allocation is handled.
  • One participant acknowledges a syntax correction made by another, reflecting on the importance of understanding concepts over mere coding.

Areas of Agreement / Disagreement

Participants express varying levels of understanding regarding the use of pointers and references in C++. While some agree on the mechanics of passing by reference, others highlight different approaches and potential pitfalls, indicating that the discussion remains unresolved on certain points.

Contextual Notes

Participants mention issues related to memory management, such as the need to deallocate arrays and the implications of changing pointers within functions. There are also concerns about the correctness of calculations related to binary conversion and the handling of dynamic arrays.

Who May Find This Useful

This discussion may be useful for individuals learning C++ programming, particularly those interested in understanding pointers, references, and memory management in the context of function implementation.

rootX
Messages
480
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++.
 

Similar threads

  • · Replies 17 ·
Replies
17
Views
2K
Replies
89
Views
7K
  • · Replies 35 ·
2
Replies
35
Views
4K
  • · Replies 31 ·
2
Replies
31
Views
3K
  • · Replies 23 ·
Replies
23
Views
3K
  • · Replies 36 ·
2
Replies
36
Views
3K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K
Replies
4
Views
2K
  • · Replies 13 ·
Replies
13
Views
2K