PDA

View Full Version : My newbie C++ questions


Zegg90
12-08-2006, 09:17 PM
I have a few questions that probably have very simply answers :P
I am learning C++, and it's easy in some aspects but in others I am very confused...

1. I've seen some object examples, but what's the difference between these two:
Object1.Function();
Object1->Function();
Is the dot used or the arrow used? For both functions and variables?

2. How are pointers used in functions?
I've seen Get() functions that take information from the class, and they require a pointer to set the retrieved value to the pointer.
But the Set() function just needs a normal variable, and not a pointer...
This is the code:
BOOL Get(DWORD *Var) { *Var = m_dwCount; return TRUE; }
BOOL Set(DWORD Var) { m_dwCount = Var; return TRUE; }

Why a pointer in one function, but not in the other?

That's about it for me at the moment :P
Thanks!

oracleguy
12-08-2006, 10:15 PM
1) It depends if Object1 is a pointer to an instance of Object1 or not.

The arrow operator dereferences the pointer when you go to access the member functions. Let's say you had this code:
string mystr;
string* p = &mystr;

You can use the dot operator on mystr but you'd need to use the arrow operator on p.

(*p).c_str();
p->c_str();
Both of these lines of code will do the same thing, however as you can see using the arrow operator is less typing.

Daniel Israel
12-12-2006, 02:25 AM
2. How are pointers used in functions?
I've seen Get() functions that take information from the class, and they require a pointer to set the retrieved value to the pointer.
But the Set() function just needs a normal variable, and not a pointer...
This is the code:
BOOL Get(DWORD *Var) { *Var = m_dwCount; return TRUE; }
BOOL Set(DWORD Var) { m_dwCount = Var; return TRUE; }

Why a pointer in one function, but not in the other?


Both functions are returning a BOOL that tells you if it succeeded or not. You can't change the value of a parameter, so if you want to change something outside the function, you have to do it through a pointer. Set doesn't do that, and therefore doesn't need a pointer.

Zegg90
12-12-2006, 08:28 PM
Ah, okay, thanks! I understand now :)