Basic questions from a newbie...

Hi all,

I'm an absolute beginner in using C++. I have some knowledge in programming in Java, but none with C++. Now I have to understand a C++ source code and have a lot of difficulties to do so...
My first questions (other will follow for sure...):
- The source code is divided into two parts per class. One part is named something.h, the other something.cpp. Am I right, that this works like interfaces in Java? When do I use headers.
- What do the first two lines of code "#ifndef _something_" and "define _something" mean?
- What do the leading * and the the leading & in front of a variable mean? I suppose, * is a pointer, but what is the &?

Thanks a lot for you help!

Nell
1) Yes.

2) ifndef (if not defined), define, and endif are used to keep chunks of code from being included twice. It may be easier to visualize with brackets (don't actually use them though):
1
2
3
4
#ifndef STUFF {
    #define STUFF
    // code for STUFF
} #endif 

If STUFF is not defined, the code between ifndef and endif will be included and STUFF will be defined. If STUFF is already defined, this code will not be included.

3) & is a reference. I think Java has those, but I've never used Java so I'm not sure.
The source code is divided into two parts per class. One part is named something.h, the other something.cpp. Am I right, that this works like interfaces in Java?

Just wanted to add that the code separation (separating an interface from an implementation) is not the same as the keyword interface in Java.

Interfaces in Java would be more like a base class with virtual functions in C++ (C++ allows for "multiple inheritance", which Java avoids).
http://stackoverflow.com/questions/318064/how-do-you-declare-an-interface-in-c
Last edited on
Thank you guys for your help!

One more question on the * and & operator. The * is a pointer, the & a reference. What is the difference between the two? I tried to write some line of code, but I can't see the difference between the two things.
They are similar, C++ compilers translate references to pointers behind the scenes.

Here's a comparison
Using references:
1
2
3
4
5
6
7
void withdraw(double& balance, double account)
{
    if (balance >= amount)
        balance = balance - amount;
}
//have to call it like this:
withdraw(johnnys_balance, 1000);

Using pointers:
1
2
3
4
5
6
7
void withdraw (double* balance, double amount)
{
    if (*balance >= amount)
        *balance = *balance = amount;
}
//have to call it like this:
withdraw(&jimmys_balance, 1000);

As you can see, using references instead makes the code read more "fluently" (at least to me) since you can just pass in "my_balance" whether or not the function has it as a reference parameter or not, and using reference syntax instead of pointers is usually preferred.
Topic archived. No new replies allowed.