When to use pointers and when to use references in c++. plz clear my doubt.. thnks in advance
dasari.prasad 0 Newbie Poster
elsiekins 0 Junior Poster
http://www.cplusplus.com/doc/tutorial/pointers/
http://www.cplusplus.com/articles/EliteHussar1/
Hopefully these articles might help
jakesee 0 Junior Poster
I have am working on a project and have some funny usage for references. Just my two cents:
class Vector
{
public:
float v[3];
float &x, &y, &z;
// we can access the x, y, z values in both ways.
// note that a union clause can achieve the same effect.
Vector3():x(v[0]), y(v[1]), z(v[3]) {}
};
class Data
{
private:
// Threaded Processor
class Processor
{
// many many variables
// required for processing
// but hogs memory...
process(float* &destination)
{
subprocess();
destination = new float[100];
}
subprocess() {}
};
float* values;
load()
{
loader = new loader();
loader.process(values);
delete loader;
}
};
Edited by jakesee because: n/a
Fbody commented: Just showing off, doesn't help the OPs question. +0
Fbody 682 Posting Maven Featured Poster
Pointers and references are similar and are both used under similar circumstances. Really, a reference is just a pointer without all the extra syntax, but they are not freely interchangable. Which syntax you use for function calls depends on how the function being called is defined. Both are frequently used to allow a function to modify the contents of an argument to the function call and/or improve the efficiency of certain types of function calls. They can be used for other reasons, but these are the primary reasons a beginner needs to be concerned with.
Case 1, allow a function to modify an argument:
In general, a function can not modify the value(s) of the argument(s) used to call it. But this can be changed.
//example of standard function call
#include <iostream>
void standardHelloNumber(int a) {
a = 20;
std::cout << "Hello o/. The number is " << a << std::endl;
}
int main() {
int a = 10;
std::cout << "a is " << a << std::endl;
std::cout << "calling standardHelloNumber(a)...\n";
standardHelloNumber(a);
std::cout << "after standardHelloNumber(a), a is still " << a << std::endl;
return 0;
}
//example of function call with pointer
#include <iostream>
void pointerHelloNumber(int *a) {
*a = 20;
std::cout << "Hello o/. The number is " << *a << std::endl;
}
int main() {
int a = 10;
std::cout << "a is " << a << std::endl;
std::cout << "calling pointerHelloNumber(&a)...\n";
pointerHelloNumber(&a);
std::cout << "after pointerHelloNumber(&a), a changed to " << a << std::endl;
return 0;
}
//example of function call with reference
#include <iostream>
void referenceHelloNumber(int &a) {
a = 20;
std::cout << "Hello o/. The number is " << a << std::endl;
}
int main() {
int a = 10;
std::cout << "a is " << a << std::endl;
std::cout << "calling referenceHelloNumber(a)...\n";
referenceHelloNumber(a);
std::cout << "after referenceHelloNumber(a), a changed to " << a << std::endl;
return 0;
}
When you compile and run these, notice how the value of a changes in main() after the call to the function in the pointer and reference versions.
Case 2, improve the efficiency of certain types of function calls:
This use case stems from the fact that it is easier (and therefore faster) to pass to a function a small 4 or 8 byte number saying where an object is located in memory than it is to pass the function a copy of a much larger complete object.
Let's build an example class:
class Example {
private:
int exampleInt;
double exampleDouble;
public:
Example(): exampleInt(0), exampleDouble(0.0) {}
setExampleInt(int newInt) { exampleInt = newInt; }
setExampleDouble(double newDouble) { exampleDouble = newDouble; }
};
Now, let's design a program to use it both inefficiently and efficiently:
#include <iostream>
using namespace std;
void inefficientFunction(Example); //pass an example object directly to function
void efficientFunction1(Example &); //pass a reference to an example object
void efficientFunction2(Example *); //pass a pointer to an example object
int main() {
Example myExample; //declare an Example object
//call functions
inefficientFunction(myExample); //inefficient function call, makes a copy of object
efficientFunction1(myExample); //efficient function call, grants function access
//to existing object, no copy made
efficientFunction2(&myExample); //efficient function call, grants function access
//to existing object, no copy made
return 0;
}
Edited by Fbody because: finished incomplete example code
Ancient Dragon commented: nice info :) +33
dasari.prasad 0 Newbie Poster
Why can't structures be compared in c..???
Fbody 682 Posting Maven Featured Poster
Directly comparing custom data structures requires operator overloading, as far as I know C can't overload operators.
To do it in C, you would have to write a custom function that has 2 structures passed in as arguments. You would then perform the comparisons and return the appropriate result. This is essentially the same as overloading an operator, the syntax is just less intuitive for the end user if they have to write if(getLesserOf(struct1, struct2) == 1)
instead of if(struct1 < struct2)
.
That's as much as I can help you on that subject, I'm still not that great with plain ol' C.
Edited by Fbody because: n/a
dasari.prasad 0 Newbie Poster
main()
{
int i=-3,j=2,k=0,m;
m=++i||++j&&++k;
printf("\n%d %d %d %d",i,j,k,m);
}
O/p is : -2 2 0 1
My doubt is , && has higher priority over ||. So here ++j&&++k will be evaluated the values of j and i not get changed .. can anyone explain this output clearly ... Thnks in advance..
Fbody 682 Posting Maven Featured Poster
When you write equations like that, your messing around with a whole lot of undefined behavior.
Indulge me a question...:
While it is true that many precedence charts indicate that Logical AND '&&' has marginally higher precedence than Logical OR '||', why would you not use parentheses to make your intentions completely clear? Why would you instead hope that you applied the precedence chart correctly?
It is far better to write
(A || B) && !(C || D)
and know that it will do what you want, than it is to hope that
A || B && !C && !D
will work as intended.
Edited by Fbody because: n/a
dasari.prasad 0 Newbie Poster
Thnks for ypur replay...
But i think u have not understood my doubt. in given expression "++i || ++j && ++k"
&& has higher priority over ||. so first ( ++j && ++k ) will be evaluated and also j value increased to 3 which is non zero. so next one also will be evaluated i.e k becomes 1. but finally in the output j and i values remain same. actually my doubt was after increasing the j and i values how did they contain same initial values.??
But later i came to know that Unary operators have higher priority over binary operators so first ++i will be evaluated and which is true so rest of the expression will be skipped as " true || something = True".
mrnutty 761 Senior Poster
>>In general, a function can not modify the value(s) of the argument(s) used to call it
You say that then you go ahead and disprove that! Lol, what a contradiction.
@OP: some helpful things :
1) If you have a choice, use reference over pointers
2) If you do not need to change the function argument, still use reference, but make it constant qualified like so const DataType& arg0
.
3) Using reference and pointers on basic data types such as float,int,char does not make any difference in performance, therefore you can go either way, but people usually disregard the reference and pointers on basic types, unless there is a compelling reason to do so.
The main thing you should get from this is If the argument needs to be changed use reference over pointers when possible, and If the argument does not need to be changed, use const reference if possible
ben1Greer 0 Newbie Poster
When to use pointers and when to use references in c++. plz clear my doubt.. thnks in advance
In the C++ programming language, a reference is a simple reference datatype that is less powerful but safer than the pointer type inherited from C.
# It is not possible to refer directly to a reference object after it is defined; any occurrence of its name refers directly to the object it references.
# Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
# References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid.
# References cannot be uninitialized. Because it is impossible to reinitialize a reference, they must be initialized as soon as they are created. In particular, local and global variables must be initialized where they are defined, and references which are data members of class instances must be initialized in the initializer list of the class's constructor.
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.