Using Const Object & Variables in C++ Functions

In summary: You have to make sure the array is of exactly the same size, and you have to be careful about memory leaks when you delete the old array, and if you forget either of these, you'll get a crash. So most programmers prefer one of the other two approaches.and, deallocate means "delete binary;" which should be near the main method end .. ?Well, you should deallocate it when you're done with it. In this case, when you're done with it is when you're done with it. So you might as well deallocate it right after you've used it.
  • #1
rootX
479
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
  • #2
& 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.
 
  • #3
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:
  • #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:
#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;
}
 
  • #5
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 &[color=red]rObject[/color])
// usage is
    [color=red]rObject[/color].element
I've corrected your syntax
 
  • #6
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?
 
  • #7
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];
 
  • #8
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?
 
  • #9
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++.
 

1. What is a const object in C++?

A const object in C++ is an object whose value cannot be modified after it has been initialized. This means that once a value is assigned to a const object, it cannot be changed during the program's execution.

2. What is the purpose of using const objects in C++ functions?

The purpose of using const objects in C++ functions is to ensure that the function does not modify the value of the object. This helps to prevent unexpected changes to the object's value, making the code more reliable and easier to debug.

3. How are const objects passed into C++ functions?

Const objects can be passed into C++ functions as either function parameters or function return values. In both cases, the const keyword is used to indicate that the object's value will not be modified by the function.

4. Can const objects be modified within C++ functions?

No, const objects cannot be modified within C++ functions. Attempting to modify a const object within a function will result in a compilation error.

5. How are const variables used in C++ functions?

Const variables in C++ functions are used to ensure that the value of the variable cannot be changed within the function. This helps to prevent accidental modifications and improve the overall reliability and maintainability of the code.

Similar threads

  • Programming and Computer Science
Replies
1
Views
589
  • Programming and Computer Science
Replies
17
Views
1K
  • Programming and Computer Science
Replies
5
Views
366
  • Programming and Computer Science
Replies
3
Views
1K
  • Programming and Computer Science
2
Replies
35
Views
2K
  • Programming and Computer Science
2
Replies
36
Views
2K
  • Programming and Computer Science
Replies
4
Views
1K
  • Programming and Computer Science
Replies
5
Views
812
  • Programming and Computer Science
Replies
3
Views
1K
  • Programming and Computer Science
Replies
31
Views
2K
Back
Top