You are here:

C++/difference between pointers and mem location

Advertisement


Question

hello, Bill

I still dont understand what is the difference between pointers(*var) and memory locations (&var)

for example

returnType& functionName(){

}

and

returnType* functionName(){

}

what should each return??

also, what is the difference
between calling a function as objectName->function() and
objectName.function()??

thanks

Answer
Hello,

1. int i;
2. int *i;
3. int &i;

1. i defines a location in memory that holds an integer.  The compiler reads/writes the integer using 'i';

2. *i defines a location in memory holding an address.  If the location is an address of an integer (i = &x), the compiler accesses the address using 'i' and it accesses the integer using *i.  A pointer is an address and * tells the compiler to load what is at the address (as opposed to the address itself)

3. &i is a pointer (called a reference) and it, in essence saves from having to use the * operator.  A reference to a struct allows you to use the . operator instead of the -> operator for a pointer to struct.

Returning a reference is unusual in code other than operators.  The reason it's used in operators is because you want the object returned to be the final result.  Without the reference the operator returns a temporary which has to be created and copied.

There really isn't a difference in the 2 return statements - one would have a reference passed in (you wouldn't return a reference to a stack-based object) and the other would have an address.

objectName->function() means objectName is a pointer to the class.

objectName.function() means objectName is an instantiation, not allocated.

class someClass x, *px;

These are the same:

x.y;
(&x)->y;

and these are the same:

px->y
(*px).y

Hope this helps some.

Bill

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Bill A

Expertise

I can answer questions about C++, programming algorithms, Windows programming in MFC (which is C++). I cannot answer questions about STL (templates) and I have no experience with Linux. I do enjoy reviewing code and critiquing it or finding problems in it. I will also gladly show better algorithms or methods if you want to take advantage of that.

Experience

I've developed a commercial embedded C compiler/assembler and IDE with debugger toolset, of which the IDE and debugger are written in C++. I work in the industry writing high tech embedded programs and Windows programs to communicate with the embedded devices.

Publications
Book: Embedded Systems Design using the Rabbit 3000 Microprocessor Authored Chapter 10 in its entirety.

Education/Credentials
BS Computer Engineering

©2016 About.com. All rights reserved.