C++ Syntax help

Started by
9 comments, last by _Danneman_ 21 years, 3 months ago
Im a bit confused about how the following syntax is supposed to be understood: ---------------------------- void MyFunction(vector &myVariable) {function executes stuff here...} ---------------------------- I dont understand what the stuff inside the parentesis is doing, in detail.
------------------------Why of course the people don’t want war. ... That is understood. But after all it is the leaders of the country who determine the policy, and it is always a simple matter to drag the people along, whether it is a democracy, or a fascist dictatorship, or a parliament, or a communist dictatorship ...Voice or no voice, the people can always be brought to the bidding of the leaders. That is easy. All you have to do is to tell them they are being attacked, and denounce the pacifists for lack of patriotism and exposing the country to danger. It works the same in any country. [Herman Goering]
Advertisement
Short Answer:
It passes a reference to a vector object.

Long Answer:

The ''stuff'' inside the parenthesis is the variable that is passed to the function.

Say you have a function that squares a single number.
int Square(int NumberToSquare);

To use the parameters(stuff inside the parens) you''d simply refer to them like any other initialized variable.
int Square(int NumberToSquare)
{
int SquaredNumber = NumberToSquare * NumberToSquare;

return SquaredNumber;
}

So in this example, you pass an int(NumberToSquare), initialize a final variable to the passed variable multiplied by itself(bad practice, but easier to read), and then return the squared number.

The Ampersand(&) is telling the compiler that it''s passing a reference. When a variable is passed normally, it in effect copies the entire memory of that variable for use in the function, which slows down the program and eats up more memory than needed. A reference in short(and incomplete) terms, passes only the memory address of the variable, which for all intents and purposes, acts just like the variable it points to.

I''m a little bad at explaining things, so some real gurus might need to correct me here and there.

-This is where the world drops off
-ryan@lecherousjester.com
Okay. C/C++ functions have three basic parts.


return-type name(parameter list)


If you need to return a value, say you are multiplying two numbers together and with to return their value, you need to specify what data type the return value is. The name does just what is sounds like, it gives your function a name that you can call it by. The parameter list (the stuff in parenthesis) are the values you need passed into the function for it to work properly. Take my multiplication example for instance. In order to be able to multiply two numbers, you need to have two numbers passed in to multiply. Heres an example of call by value



  int mult(int a, int b){    return a * b;}  



The items between the curly brackets just tell what to do when the function is called. If you call MyFunction in your example, then anything between the brackets occurs. Nor for the & operator. Say your function here normalizes a vector. Just pretend the name is normalize. You don''t want to return a vector everytime maybe, and write it like this



  MyVector = Normalize(MyVector);  



The & operator is the address operator. Say your function prototype is written



  void MyFunction(vector myVariable);  



It does not actually take the variable you pass into the function, it just copies the value of what you pass in, so your variable is unchanged. So rather than writing the example I had above where I set my variable equal to the return value when I call the function, I just call the address of my variable through my parameter list, so that myVariable in the parameter list is actually just an alias for you actual variable, and you actually do change the value of your variable in your function, thus you don''t need to return it. This is call by reference. Taking the normalization example from above, say my function prototype looked like this.



  void Normalize(vector &myVariable);[source]<br>then to be able to normalize your vector through the function, you would just call the function as such<br>[source]Normalize(MyVariable);  



is the same thing now as the above example where I did



  myVariable = Normalize(myVariable)  



except I don''t need to worry about a return type. You should also look into pointers, but since you don''t yet grasp functions and references yet, the I recommend waiting a while longer before you look into pointers.
Ouch, it seems I edited away a piece of the subjects title. Should have been "C++ Syntax help : pointers or reference?".
I do grasp functions and variables passed normally, but when it comes to passing pointers and references Im a bit lost. Sorry about the confusion.

Anyway, I got the answer that I needed - it is actually a reference that is being passed. Thanks guys

Two things I still didnt get though:

1) When I change &myVariable inside the function, does the variable to which &myVariable is a reference change (as opposed to normal passing of variables)?

2) Does the variable to which &myVariable is a reference to have to be a vector, or can this code create a vector reference of a normal (non-vector) variable?

[edited by - _Danneman_ on December 27, 2002 9:46:18 AM]
------------------------Why of course the people don’t want war. ... That is understood. But after all it is the leaders of the country who determine the policy, and it is always a simple matter to drag the people along, whether it is a democracy, or a fascist dictatorship, or a parliament, or a communist dictatorship ...Voice or no voice, the people can always be brought to the bidding of the leaders. That is easy. All you have to do is to tell them they are being attacked, and denounce the pacifists for lack of patriotism and exposing the country to danger. It works the same in any country. [Herman Goering]
quote:Original post by _Danneman_
1) When I change &myVariable inside the function, does the variable to which &myVariable is a reference change (as opposed to normal passing of variables)?

2) Does the variable to which &myVariable is a reference to have to be a vector, or can this code create a vector reference of a normal (non-vector) variable?

[edited by - _Danneman_ on December 27, 2002 9:46:18 AM]

It''s like this. Passing a variable by value--int myVariable--is like a copy machine. Imagine you have a copy machine and you must give a copy of your homework to a friend. You give your friend the copy and he can do anything he wants to that copy, but YOUR homework won''t be affected.

Passing by reference--int &myVariable--is more like handing a friend your original homework. He can rip it to shreds, write on it, change the answers, and when he hands it back to you later, you can only hope he did what you wanted.

Passing a pointer of your variable--int * myVariable--is like telling your friend "I left my homework in locker number 16423." He doesn''t actually have your homework, but he knows where to find it(dereferencing)--*myVariable = 10.

More stuff: arrays are really just pointers to a contiguous block of memory, you just can''t change where they point to. Pointers allow you to dynamically allocate memory during run-time. You can have pointers to functions.

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

Great analogy, nobodynews - thanx Cleared the mist in my mind some more. Can only hope for a fogg-free tomorrow.

Passing a reference enables you to edit the original variable from your inside your function. Passing a pointer or a variable essentially just gives you a copy of a variable to play with locally inside your function. Great, I think I got it :D
------------------------Why of course the people don’t want war. ... That is understood. But after all it is the leaders of the country who determine the policy, and it is always a simple matter to drag the people along, whether it is a democracy, or a fascist dictatorship, or a parliament, or a communist dictatorship ...Voice or no voice, the people can always be brought to the bidding of the leaders. That is easy. All you have to do is to tell them they are being attacked, and denounce the pacifists for lack of patriotism and exposing the country to danger. It works the same in any country. [Herman Goering]
quote:Original post by _Danneman_
Great analogy, nobodynews - thanx Cleared the mist in my mind some more. Can only hope for a fogg-free tomorrow.

Passing a reference enables you to edit the original variable from your inside your function. Passing a pointer or a variable essentially just gives you a copy of a variable to play with locally inside your function. Great, I think I got it :D


Almost right. References and pointers BOTH allow you to edit the original variable passed, and passing by value (that''s the term for passing normally, neither by pointer nor reference) just gives you a copy to play with locally in the function.

Check out cplusplus.com or other C++ reference sites out there if you want a detailed explanation of the differences between pointers and references.
quote:Original post by Dobbs
References and pointers BOTH allow you to edit the original variable passed, and passing by value (that's the term for passing normally, neither by pointer nor reference) just gives you a copy to play with locally in the function.

Almost right. A reference parameter is essentially an alias for the actual parameter. A regular variable is merely passed as a copy. But please do keep in mind that a pointer (unless passed by reference) is itself nothing but a copy - the formal parameter is not an alias for the actual parameter; it merely contains the same value : The address of whatever it points to. By dereferencing it, the data it points to (and which the pointer passed as the actual parameter also points to) can be accessed, but this does not change the fact that it is itself only a copy.

The reason I mention this is because a lot of people seem to think that passing pointers and references are the same thing - they are not.


    // Changes the data i points to to 5void ChangeMyData(int *i){  *i = 5;}// Won't do anything (except, of course, leak memory) because only the local copy is changed.void ChangeMyPointer(int *i){  i = new int;}  



[edited by - Miserable on December 27, 2002 3:23:39 PM]
sorry to post here, i just hate to register in every f***** forum only for posting one message

Anyways, my question is about C++ Syntax too.

A class A should not have access to the private members of a class B, even if a member of A is an instance of B, right?

I mean, let A = Dog, and B = Cat, then this should not compile:

class Cat {

int age;

};

class Dog {

int age;

public:

void change() {
Cat B;
B.age = 3;
};

};

int
main() {

Dog A;
A.change();
return 0;

}

since age is a private member of cat. But let''s say you replace "Cat B" with "Dog B". Now, it compiles just fine (at least in gcc, don''t remember with Visual C++), even when A.try() is accesing a private member of B. Is this C++ standard behaviour? It seems really strange
Access restrictions are per class, not per object. An object can access the private members of another object of the same class without restriction.

The "Cat B" case should not compile; the "Dog B" case should.

I think that were Dog a member class of Cat (nested type), the "Cat B" case should compile, but I can''t remember for sure - and compilers tend to barf on that anyway.

[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement