C++ For Java Programmers
C++ For Java Programmers
1. Algorithms
Algorithms act on containers.
yup. were going to end this section with: Just include the <algorithm> library.
Algorithms Exceptions Java vs. C++ : A fight to the death C++ 7 Deadly sins
Algorithms can be applied to any type of container. They often use sequences these are a list of elements defined by a starting and finishing iterators (eg. v.begin() and v.end() ).
Reversing a Sequence
The reverse() algorithm reverses the order of a range specified by its start and end iterators.
Initially v contains:
for(i=0; i<10; i++) { if (rand() % 2) v.push_back(true); else v.push_back(false); } counts the no. of trues
0123456789
int matches = count(v.begin(), v.end(), true); cout << matches << elements are true.; }
for_each
using for_each we can apply a function to every single element of our container.
int main() { vector <string> tubbies; v.push_back( dipsy ); v.push_back( lala ); v.push_back( po }
OUTPUT: DIPSY LALA PO
Sorting a Sequence
Sort() is an incredibly useful algorithm that you can use on any container it too uses a sequence.
int main() { vector <int> v;
Initially v contains: 3522378610
2. Exceptions
The purpose of this section is to explain how to:
detect erroneous conditions to signal such conditions to your program to work out what on earth do with them
The aim is to give you the knowledge to extend your programs to correctly throw and catch exceptions when run-time errors arise. This is crucial in all professional programs. In courseworks handling exceptions =marks.
Synchrony
Exceptions in C++ are synchronous they are used for error handling, such as failures during array bounds checking. Asynchronous exceptions such as timer or keyboard interrupts are not handled directly by the language. Most systems provide some mechanism for handling asynchronous exceptions such as UNIX signals but since these features are system-dependent, they are excluded from C++ itself.
Dividing by ZERO
Imagine we have a class that stores fractions. One of its methods would be used to set the denominator.
void Fraction::setDenominator(int d) { denominator = d; }
But if this denominator is set to zero when we try to use the fraction its going to make our program collapse in a heap in the corner as it tries to divide by zero. We need to use an exception-handler!
Catch Handlers
A catch handler resembles a function definition:
Trying
Code that deals with the situations in which exceptions can arise directly or indirectly through function calls is put in a try block
Throwing
If an errant situation is detected a throw statement is invoked. This passes information about the error to the exception handler.
A catch handler begins with the keyword catch and a singleparameter list. The type of exception should match a type of exception that can be thrown from the try block. Following this is the catch statement block this is executed if the catch handler is invoked to process an exception.
Catching
Following the try block are the catch-exception handlers. There is typically a catch handler for each possible type of exception in the try block.
Equally we can have more than one catch block the one that matches the throw type will be executed:
catch(int i) { cout << uppercase letters not allowed; } catch(float f) { cout << lowercase letters frowned upon; } catch(char c) { cout << full stops are banned too; }
try {
try {
try {
if a catch is not the right type the flow will go up the nest
catch {
} catch { }
} }
catch {
int main() { try { func(); } catch( bad_alloc) { cout << memory error; } }
Types of Exception
The exceptions that we have looked at have tended to be made by us. However if we include <exception> library, we get lots of exception classes that represent errors. We can use these in the catch statement for example:
bad_alloc bad_cast overflow_error invalid_argument - thrown by new when it has a problem - thrown automatically when a cast fails - Arithmetic overflow. - Incorrect arg was used in a function call
Exception Hierarchy
exception
bad_alloc
bad_cast
bad_exception
bad_typeid
ios::failure
logic_error
runtime_error
domain_ error
invalid_ argument
out_of_ range
overflow _error
underflow _error
range_ error
Summary of Exceptions
exceptions don't spare you the effort of handling errors. They do provide the means to separate all the grungy details of what to do when something out-of-theordinary happens from the main logic of your program. You can write your own throws or use the ones provided in the C++ standard library.
Classes
1.
Data types almost identical C++ has extra short and unsigned types. The Boolean type is called bool in C++. C++ strings store ASCII characters, not Unicode characters To compare strings, C++ uses == != < <= > >=. The last four operators perform lexicographic comparison. This is actually more convenient than the use of equals and compareTo in Java. The C++ compiler does not check whether all local variables are initalized before they are read.
In C++, there are public and private sections, started by the keywords public and private. In Java, each individual item must be tagged with public or private - this is a pain. The class definition only contains the declarations of the methods. The actual implementations are listed separately in C++. Accessor methods are tagged with the keyword const in Java. There is a semicolon at the end of the class in C++.
2. 3.
2.
4.
3.
5.
4.
Objects
The major difference between Java and C++ is the behaviour of object variables. In C++, object variables hold values, not object references. The new operator is never used when constructing objects in C++. You simply supply the construction parameters after the variable name. This is often preferable, but when modifying an object in a function, you must remember to use call by reference in C++.
Functions
In Java, every function must be an instance method or a static function of a class. C++ supports instance methods and static functions of classes, but it also permits global functions. Java does not support default arguments Java does not support inline functions. Java does have built in multithreading support
Pointers
C++ pointers are very much like Java object variables. There is, however, an essential syntactical difference. You must apply the * operator to access the object to which a pointer points. If you do not initialise a pointer, or if the pointer is NULL or refers to an object that no longer exists, then it is an error to apply the * or -> operator. Unfortunately, the C++ runtime system does not check against these errors. Java has a garbage collector - In C++, it is the responsibility of the programmer to manage memory.
Inheritance
The basic syntax for inheritance is similar in C++ and Java. In C++, you use : public instead of extends to denote inheritance. By default, functions are not dynamically bound in C++. If you want which dynamic binding for a particular function, you must declare it as virtual.
I teach C++ but the slides are displayed on the web page using a java applet.
7. Using Uninitialised Variables 6. Dereferencing a Null Pointer 5. Forgetting Copy Constructors 4. Memory Leaks 3. Out of Bounds Array access 2. Using = instead of == 1. forcing someone to use the g++ compiler