473,399 Members | 2,478 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

How to pass by reference in C++ .net?

Expand|Select|Wrap|Line Numbers
  1. int y;
  2. void square(int x, int& result)
  3.     {
  4.      result = x*x;
  5.      }
  6. ...
  7. square(3,y);
  8.  
this code compiles and works in DevCpp (native C++), but not in VS2008 .net C++

it says: error C2664: cannot convert parameter 2 from 'int' to 'int &' (on the line where i call the function)


can someone please tell me what can be done?
Oct 4 '08 #1
8 11332
looker
18
Try this :

1. int y;
2. void square(int x, int *result)
3. {
4. *result = x*x;
5. }
6. ...
7. square(3, &y);
Oct 4 '08 #2
it now says: error C2664: cannot convert parameter 2 from 'cli::interior_ptr<Type>' to 'int *' on the same line.

the more i think about it the original code should not work at all? the function body says: the address of y = x*x
not: the value on the addres of y = x*x as it should?

please correct me if i'm wrong, as i am a noob. :)

your code makes much more sence!

and guess what, it does work! thank you very much!
it just needed a minor adjusment, based on the error output.

Expand|Select|Wrap|Line Numbers
  1. int y; 
  2. square(int x, interior_ptr<int> result)
  3.      {
  4.      *result = x*x;
  5.      }
  6. ...
  7. square(3,&y);
i used this for reference: http://msdn.microsoft.com/en-us/libr...xx(VS.80).aspx

of course i like the original code much better because it seems simpler. does anyone know why it compiles in DevCpp native c++, and not in C++/CLR? or has an idea how to simplify the solution that does work?
Oct 4 '08 #3
weaknessforcats
9,208 Expert Mod 8TB
This code:
Expand|Select|Wrap|Line Numbers
  1. int y; 
  2. void square(int x, int& result) 
  3.     { 
  4.      result = x*x; 
  5.      } 
  6. int main()
  7. {
  8.     square(3,y); 
  9. }
  10.  
compiles and links on my Visual Studio.NET 2008.

There's something you're not telling us.
Oct 4 '08 #4
These are the steps I’ve taken to try this out, and indeed I take whenever I’m making an application.

In visual studio 2008 I click on file>new>project, select visual c++ in project types and windows forms application in templates.

In an 'empty' project I get a 'Form.h'. The last lines in that file are:
Expand|Select|Wrap|Line Numbers
  1. #pragma endregion
  2. };
  3. }
I write my code between lines 1 and 2.

This is how it looks:
Expand|Select|Wrap|Line Numbers
  1. #pragma endregion
  2.     int var1;
  3.     int var2;
  4.  
  5.     //SHOULD WORK
  6.     /*
  7.     public: void square(int x, int& result) {
  8.                 result = x*x;
  9.             }
  10.     */
  11.  
  12.     //DOES WORK
  13.     public: void square(int x, interior_ptr<int> result) {
  14.                 *result = x*x;
  15.             }
  16.  
  17.     //SHOULD WORK
  18.     /*
  19.     public: void swap (int& x, int& y) {
  20.                 int temp = x;
  21.                 x = y;
  22.                 y = temp;
  23.             }
  24.     */
  25.  
  26.     //DOES WORK
  27.     public: void swap (interior_ptr<int> x, interior_ptr<int> y) {
  28.                 int temp = *x;
  29.                 *x = *y;
  30.                 *y = temp;
  31.             }
  32.  
  33.     private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
  34.                  var1 = 5;
  35.                  var2 = 9;
  36.              }
  37.  
  38.     private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
  39.                  textBox1->AppendText("BEFORE SWAP - Var1: " + var1.ToString() + " Var2: " + var2.ToString() + "\r\n");
  40.                  //swap(var1,var2);
  41.                  swap(&var1,&var2);
  42.                  textBox1->AppendText("AFTER SWAP - Var1: " + var1.ToString() + " Var2: " + var2.ToString() + "\r\n");
  43.              }
  44.  
  45.     private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {
  46.                  textBox1->AppendText("BEFORE SQUARE (var2 = var1^2) - Var1: " + var1.ToString() + " Var2: " + var2.ToString() + "\r\n");
  47.                  //square(var1,var2);
  48.                  square(var1,&var2);
  49.                  textBox1->AppendText("AFTER SQUARE (var2 = var1^2) - Var1: " + var1.ToString() + " Var2: " + var2.ToString() + "\r\n");
  50.              }
  51. };
  52. }
I’ve added two buttons for calling the pass by reference functions to best simulate practical use and a textbox (multiline, with vertical scrollbar) to act as a console. The last three functions are event handlers. The first one is called on load to init the variables. The other two handle the button clicks.

Can you please elaborate on the steps you've taken? How do you start a new project and where do you write your code?

It’s the only thing I can think of that could make a difference. It’s quite possible I’m doing something horribly wrong...
Oct 6 '08 #5
It should work.
call by referece means you have to take like that only
void mul(int a, int& sum)
{
sum=a*a;
}

void main()
{
int a=10;
int sum;
mul(a,sum);
printf("%d",sum);
}

in this case i will print 100 thats sure.. i wont give any error try this agian and let me know if not...............
Oct 6 '08 #6
l034n
15
Ok, i see some things have been confused here and it has to do with the way the variables are declared... The example of vinayvaka will work as will many of the above examples (even though they didn't work for BahatiSiD). So, why?
Or... although the example of vinayvaka works as it is, if BahatiSiD tries it with his variables, it won't, i guarantee you that.
Well, BahatiSiD have declared his variables on the heap, hence they're not local variables allocated on the stack. You may ask what does it have to do with all this, but remember that this is MC++ and not ANSI C++. So, you can't pass the variables that are on the heap the same way as the local variables. The problem is that in a managed environment, the address of a variable allocated on the heap might change (and will change during the lifetime of a program numerous times, hence it is not safe to use it that way).
I could write this function:

Expand|Select|Wrap|Line Numbers
  1. void Swap(int& x, int& y)
  2.     {
  3.         int temp = x;
  4.         x = y;
  5.         y = temp;
  6.     }
  7.  
and using textBoxes as in BahatiSiD's example call it this way:

Expand|Select|Wrap|Line Numbers
  1. int num1 = 15;
  2. int num2 = 30;
  3.  
  4. textBox->AppendText("--------------------" + Environment::NewLine);
  5. textBox->AppendText("BEFORE x = " + num1.ToString() + ", y = " + num2.ToString() + Environment::NewLine);
  6. Swap(num1, num2);
  7. textBox->AppendText("AFTER  x = " + num1.ToString() + ", y = " + num2.ToString() + Environment::NewLine);
  8.  
and it will work like a charm. But, if i call it this way:

Expand|Select|Wrap|Line Numbers
  1. textBox->AppendText("--------------------" + Environment::NewLine);
  2. textBox->AppendText("BEFORE x = " + var1.ToString() + ", y = " + var2.ToString() + Environment::NewLine);
  3. Swap(var1, var2);
  4. textBox->AppendText("AFTER  x = " + var1.ToString() + ", y = " + var2.ToString() + Environment::NewLine);
  5.  
I'll get an error:
error C2664: 'TestProject::Form1::Swap' : cannot convert parameter 1 from 'int' to 'int &'

Note that i just used BahatiSiD's variables as he has declared them. I am making this example so that BahatiSiD can try it out in his sample project.
So, what the heck...
We're telling the compiler that Swap() takes 2 int&, and it's fine, but why in the first example the compiler passed our variables by-reference, and the second time it did not?
As i previously said, you cannot use ordinary native C++ pointers with the garbage-collected heap because if the location of the data pointed to changes, the pointer will no longer be valid.
So, what we need now is a way to access the object on the heap that enables the address to be updated when the gc will reallocate the data item on the heap. We have 2 ways at our disposal:
1. Tracking handle (or simply, handle), which is analogous to a pointer in native C++
2. Tracking reference (equivalent to a reference in native C++)

So... they act pretty much as their counterparts in native c++ (as much as the programmer might be concerned, although he should understand the fundamental differences, because they really are different), but don't forget the keyword TRACKING. They track the address of the object on the heap, so you always have a valid pointer/address.
That's why the examples with interior_ptr<int> worked, because interior_ptr<Type> is managed by the CLR and the address is accordingly updated whenever the GC collects.
So, in order to make it work, you may use interior_ptr<int>, or if you want to use the forementioned Swap() function (or any other function of that type) and make it work, you may "cheat" a little bit this way:

Expand|Select|Wrap|Line Numbers
  1. int num1 = var1;
  2. int num2 = var2;
  3.  
  4. textBox->AppendText("--------------------" + Environment::NewLine);
  5. textBox->AppendText("BEFORE x = " + num1.ToString() + ", y = " + num2.ToString() + Environment::NewLine);
  6. Swap(num1, num2);
  7. var1 = num1;
  8. var2 = num2;
  9. textBox->AppendText("AFTER  x = " + num1.ToString() + ", y = " + num2.ToString() + Environment::NewLine);
  10.  
What we do here is, we allocate 2 int variables on the stack, initialize them with the values of the heap variables, swap them and store the resulting values back to the heap variables.
I wouldn't go in details here about the tracking types (maybe in some other thread) as the post is large as it is without it, but i hope you understand what were you doing wrong in your approach and how to work around the problem.

Cheers
Oct 6 '08 #7
That seems about right!

As it stands I’m writing my code in a ref class which is Form1 and when I declare an int outside of a function (which is then a member function of Form1) it's just a member variable of a ref class so I guess it's on the heap too.

This clearly isn't the way to go, so it's back to the drawing board for me. :)

Can someone point me in the direction of a fairly comprehensive managed c++ windows forms sample project? I’ve looked at the examples provided with VS2008 but I’m having trouble compiling them.
Oct 7 '08 #8
pass by reference is different in .NET C++, and there is definitely an easy way to do. I've come across the answer before, but forgot.

I know this isn't a direct answer to the question....but I think it might clear matters up.
Dec 10 '09 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

110
by: Mr A | last post by:
Hi! I've been thinking about passing parameteras using references instead of pointers in order to emphasize that the parameter must be an object. Exemple: void func(Objec& object); //object...
4
by: z_learning_tester | last post by:
I'm reading the MS press C# book and there seems to be a contradiction. Please tell me which one is correct, 1 or 2. Thanks! Jeff 1. First it gives the code below saying that it prints 0 then...
5
by: David++ | last post by:
Hi folks, I would be interested to hear peoples views on whether or not 'pass by reference' is allowed when using a Web Service method. The thing that troubles me about pass-by-reference into...
4
by: Jon Slaughter | last post by:
I'm reading a book on C# and it says there are 4 ways of passing types: 1. Pass value type by value 2. Pass value type by reference 3. Pass reference by value 4. Pass reference by reference. ...
14
by: Abhi | last post by:
I wrote a function foo(int arr) and its prototype is declared as foo(int arr); I modify the values of the array in the function and the values are getting modified in the main array which is...
10
by: Robert Dailey | last post by:
Hi, I noticed in Python all function parameters seem to be passed by reference. This means that when I modify the value of a variable of a function, the value of the variable externally from the...
6
by: lisp9000 | last post by:
I've read that C allows two ways to pass information between functions: o Pass by Value o Pass by Reference I was talking to some C programmers and they told me there is no such thing as...
11
by: venkatagmail | last post by:
I have problem understanding pass by value and pass by reference and want to how how they are or appear in the memory: I had to get my basics right again. I create an array and try all possible...
15
by: ramif | last post by:
Does call by reference principle apply to pointers?? Is there a way to pass pointers (by reference) to functions? Here is my code: #include <stdio.h> #include <stdlib.h>
12
by: raylopez99 | last post by:
Keywords: scope resolution, passing classes between parent and child forms, parameter constructor method, normal constructor, default constructor, forward reference, sharing classes between forms....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.