Learning Objectives
- Explain the difference between interpolated and compiled programming languages.
- Describe some potential advantages of object-orientated programming over other programming paradigms.
- Write simple C++ programs making good use of variables, constants, expressions, assignment statements I/O, basic data types, comments and pre-defined functions.
All programming languages can also be classified as either interpreted or compiled:
Interpreted languages, execute a program straight away after it has been written in real time. However with compiled languages an intermediate step, called compilation is performed.
Compilation refers to the process of translating a ‘high-level’ computer program into machine code, which is the ‘low-level’ language that the computer’s central processing unit (CPU) can execute. MatLab can be either interpreted or compiled, but is mostly used as an interpreted language.
Compilation translates the high-level (C++) code, which is contained in the source files, into object files. These object files contain machine-readable instructions. However these instructions are not machine-executable unless they are linked to a library/other parts of a program enabling the machine to understand what to do with the files. This thinking can be paralleled with a lego car box set. Without instructions anything can be made with the lego bricks. But only with the specific parts/library of instructions can the lego bricks be made into specific model of car as shown on the box.
Another major difference between programming languages lies in their programming paradigms:
Historically the dominant paradigm. Procedural programs work by executing a sequence of instructions provided by the programmer.
This is a lesser known paradigm. With declarative programs, statements are declared about/how a problem can solved, regardless of their order.
In the late 1980s there was a shift in the dominant paradigm from procedural programming to object-oriented programming. Object orientated programs allow the programmer to break down problems into objects. Where objects are self-contained entities consisting of both data and operations on the data.
C++ extends the existing procedural programming language, C. Therefore, C++ is not a pure OOP language, but rather a mixture of procedural and OOP.
In OOP languages, instead of writing sequences of instructions, the programmer defines objects with attributes and behaviours. The objects communicate with each other, sending data, and requesting certain behaviours to be carried out. All OOP languages have the following three features:
Also known as information hiding, it separates the logical properties of a data structure (what it does) from implementation details (how it does it).
It is a common technique that the human mind uses to tackle complex problems: break the problem down into smaller, simpler, well-defined sub-problems and solve each individually. By specifying the required inputs and outputs of a sub-problem we are abstracting away from the main problem.
This is a way of reusing code from existing objects. One object can inherit all of the attributes from existing objects, then more can be added.
Inheritance can lead to more reliable and easily understandable software
Polymorphism describes taking on many different forms. In OOP, it refers to objects having type dependent attributes/behaviours.
Dynamic binding is a related concept. It means waiting until run-time before deciding which type-dependent operation to use on an object.
Many OO features are aimed at allowing greater code reuse. This is beneficial for the following reasons:
OO design involves forming a model of the problem domain. The problem domain consists of objects with relationships between them. There are three types of relationships:
Most Integrated Development Environments (see next section) come with a useful debugger to help find errors in the code, and they help with the following:
C++ is uses static type checking, whereas matlab uses a dynamic form of type checking.
The validity of operations are based on data types of operands and is checked at run-time.
The validity of operations are checked at compile time.
There are several different integrated development environments (IDE) available to code, build and run C++ programs. These software packages define projects consisting of source code, specify compilation options and run the compiled code. Users running Windows/Linux should download Code::Blocks and Mac users should install CodeLite:
Note: Remember to check that you have a compiler installed!
The default program that loads in most IDE’s when you start a new project is the hello world program. This is the base template for all C++ code and syntax:
// hello world program
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world" << endl;
return 0;
}
This program can be broken down into a few key components:
main () {}
is all code that is to be executed is contained in the function called main, which is delimited by {…}.
NOTE: Function arguments : go inside the brackets ()int
refers to the ‘return type’ of the main function (ie. the data type of the output);
unlike in Matlab where the semicolon only suppressed the line, C++ uses the semi-colon to identify the end of the line.
NOTE: All commands must end in semi-colonscout
sends characters to standard output which is in most cases the screenendl
is an end-line character and send the cursor to the next line (not dissimilar to \n)return 0
this line is a convention that indicates that the program has terminated successfully//
indicates a comment (the C++ equivalent of % in Matlab). It can be used over multiple lines using /* …..*/#include
causes another source file to be included. The functions defined by other source file can be used without compilation errors. In this case the iostream file includes details of the cout functionusing namespace '---'
tells the compiler the particular namespace, in this case std (standard) is used which includes cout, endlPreprocessing step is where the #include
files are added. It occurs before compilation and includes all the required source files.
The code below demonstrates a more complex program which includes variables and expressions:
// arithmetic program
#include <iostream>
#include <math.h>
using namespace std;
int main() {
int x, sq_x;
cout << "Enter a number:" << endl;
cin >> x;
sq_x = x*x;
cout << "sq. root=" << sqrt(x) << endl;
cout << "square = " << sq_x << endl;
cout << "cube = " << sq_x*x << endl;
return 0;
}
#include math.h
defines some mathematical functionsint x, sq_x;
defines the return type of the data as integer and the variables as x and sq_x. Unlike Matlab all variables must be declared and their type specifiedcin
statement reads from standard input (the keyboard)In the arithmetic program above various operators are used, and they are summarised in the following table, with their precedence listed in the table below:
Arithmetic operators | |
---|---|
Basic | + - * / |
Modulus (remainder) | % |
Increment/decrement | ++x x++ --x x-- |
Note: the difference between the prefix and postfix versions of increment/decrement operation lies in whether the value is returned before (posfix) or after (prefix).
Operator precedence | |
---|---|
First | increment, decrement |
Second | multiplication, division, modulus |
Third | addition, subtraction |
In c++ we must explicitly declare the type of all variables. The basic types are:
Be careful with using operations with different data types, you can’t use modulo on bool or char. In reality we cant add bool and char, however if you attempt to in C++ a bool will be converted into 1 or 0 and char into their respective ASCII values.
Note: Integer arithmetic can be different to floating point arithmetic. i.e. 1/3 evaluates to 0 because two integer inputs will force an integer output. To fix this use a float input: 1.0/3 equates to 0.33
const
declares an identifier that it wont change its value:
const double pi = 3.1415926
The #include
statement can be used to include external files that make use of pre-defined functions and a few examples re given in the table below:
Header | Function | Arg | Operation |
---|---|---|---|
stdlib.h | abs(i) | int | Absolute (int) |
math.h | cos(x) | float | Cosine(x) (radians) |
math.h | fans(x) | float | Absolute (float) |
math.h | pow(x,y) | float | xy |
math.h | sin(x) | float | Sine(x) (radians) |
math.h | sqrt(x) | float | Square root of x |
math.h | tan(x) | float | Tangent(x) |