The biggest hurdle in making the transition from Java to C++ is understanding pointers. Pointers behave exactly like references in Java (in fact, references are usually implemented as pointers). The difference is that in Java all objects are treated as references, and you cannot make a reference to a primitive type (int, bool, float, etc). As a result, Java doesn't need a special pointer type. In C++ you can have both, so the language needs to distinguish between a type and a pointer to that type. Here are some simple examples...
This following Java code creates an instance (object) of a Car class.
Car c; // Declare a reference to a Car (there is no actual Car object yet) c = new Car; // Now c refers to a Car object c.speed = 5; // Cross the reference, set the speed Car d = c; // c and d refer to the same Car d.speed = 10; // same as saying c.speed = 10
Here is the equivalent C++ code:
Car * c; // Declare a pointer to a car (also no actual Car object yet) c = new Car; // Make a new Car object, pointed to by c c->speed = 5; // Cross pointer, set speed Car * d = c; // Make a copy of the pointer d->speed = 10; // same as saying c->speed = 10
The simple rule is this:
Wherever you would use a reference to a Java object, in C++ you must use a pointer to the object.
C++ also has the ability to declare objects locally, without using new -- something that you cannot do at all in Java:
Car c; // Creates an actual car object -- no pointers, no references, no call to new c.speed = 5; // set speed on c Car d = c; // Make a new Car d which is a copy of Car c d.speed = 10; // no effect on Car c
Also impossible in Java: taking the address of a primitive type:
int x; int * px = &x; // px gets the address of x (*px) = 7; // Same as assigning to x
Finally, C++ does not have garbage
collection, so each object you create with new you must
explicitly free using delete, or you will eventually run out of
memory.
Car * pc = new Car; // Do something with pc // ... delete pc; // Done, free the space at that address
Back to Comp15.