Advertisement

C++ stuff

Started by March 10, 2000 01:18 AM
4 comments, last by HellStorm 24 years, 6 months ago
Hey, could someone tell me what the advantages are from passing a reference to a large class within a function as opposed to using pointers example: void dosumthin(sumclass & myclass) { //do whatever } //versus void dosumthin(sumclass * myclass) { //same } thanx
1. You don''t have to check whether the pointer is NULL or invalid within the called function. Saves you a check.

2. The caller must send a valid object reference. By using references, you can enforce this at compile time.

Note that when sending a pointer, you might in fact want to treat it as an array. You can''t do that with just references.

BTW, if you aren''t going to modify the object within the called function, you should specify it as a const reference.

void dosumthin(const sumclass& myclass)
{
...
}

Advertisement
I read in my c++ book that when u use references instead of pointers that it was faster in the cases of classes because the class object did not have to be copied, thus when modifying the data it modified the class directly. Is this true?.
The & and * operators work to together to reference and dereference pointers. The only difference is that you use & to pass the address of a pointer, whereas you use * to create a pointer. Therefore there is no difference in speed. If you use classes, the class object is not copied in either case.

--Antz
Quanta
http://quanta.virtualave.net
Be VERY carefull with references though! If the type/class isn''t the EXCACT same asin the defenition of the function then an anonumys variablewill be created by the compiler wich isn''t at all what we wan''t. Not at all. So exceptfor that, there is no realdifference in speed or so, it is more or less a matter of taste.
Right. Then you need to use the dynamic_cast operator to get it all correct.

And, if I''m not mistaken, there is no difference in speed since references are just pointers made earier to deal with in a notational and syntactical sense. I hate ''em. =) Just use pointer for real while non-assembly languages still have them. =)

This topic is closed to new replies.

Advertisement