Solved

How do you pass a C++ array element by reference?

Posted on 2011-03-14
3
590 Views
Last Modified: 2012-05-11
How do you pass an individual C++ array element by reference?  Is this possible?

Suppose you have the following class and array.  How would you pass an element of that array into some function while changing the actual element of that array as well as the members of that class instance?

class MyClass
{
     public:
          int member1;
          int member2;
          float member3;
};

MyClass myClassArray[ 10 ];

Open in new window

0
Comment
Question by:CucumberBilly
  • 2
3 Comments
 
LVL 40

Accepted Solution

by:
evilrix earned 125 total points
ID: 35131670
You mean something like this?
void foo(MyClass & c)
{
   // modify c
}


MyClass myClassArray[ 10 ];


foo(myClassArray[1]); // modify the 2nd element of the array.

Open in new window

0
 

Author Closing Comment

by:CucumberBilly
ID: 35131855
Thanks, I didn't realize you could use the same reference operator in a function for array elements.
0
 
LVL 40

Expert Comment

by:evilrix
ID: 35131923
A single array element is both semantically and syntactically identical to its scalar counterpart.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

820 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question