2CPP02 - C++ Primer
-
Upload
michael-heron -
Category
Software
-
view
70 -
download
1
description
Transcript of 2CPP02 - C++ Primer
C++ PRIMERMichael Heron
Introduction• It’s my understanding that you all learned Java as your
main language last year.• That puts you in a relatively good place for learning C++
• They are somewhat similar languages.
• Where possible, C++ code will be related back to Java in example code.• This is not possible in all circumstances.
Java versus C++• The biggest differences, as far as this module is
concerned, are as follow:• Java is a platform independent programming language.
• C++ is not
• Java is a pure object oriented language.• C++ is not
• Java handles memory management transparently• C++ requires explicit memory management
• Java hides the details of passing by value and reference.• C++ requires explicit handling
• Java permits single inheritance only• C++ permits multiple inheritance.
Pure OOP• Java is a pure object orientation language.
• All code must belong to a class.
• C++ permits a mix and match approach.• This is stylistically bad.
• For this module, your C++ code should be, as far as is possible, written as if it were pure object orientation.
• It is possible to have variables and functions that are not part of a class in C++.• This will be Frowned Upon
A Simple C++ Program#include <iostream>
using namespace std;
int main() { cout << "Hello World!" << endl; return 1;}
More C++ Differences• This simple C++ program highlights several differences to
Java programs.• First of all, line 1:
• #include <iostream>
• This is known as a preprocessor directive.• Before any of your C++ code is compiled, the compiler runs a
process called the preprocessor on it.• It’s essentially a very powerful search and replace routine.
• The #include directive tells C++ to take the file iostream.h and include it, in its entirety, in the current file.• More on the preprocessor later.
More C++ Differences• The second line:
• using namespace std;
• This is something akin to an import in Java.• It tells C++ we are going to be using the classes and methods that
make up the std set (primarily this is input and output).
• We begin execution from a main method, just as with a Java program.• However, in C++ this main method is never contained within a
class.
More C++ Differences• In Java we use System.out.println to print text to the
console.• In C++ we make use of an IO Stream… specifically, the
cout. This represents the standard output stream. It is defined in std.• The << operator is used to send data to the stream.• endl is a special symbol – it represents an end of line.
• A \n symbol essentially.
Creating a C++ Project in Visual Studio
• There are many development environments available for C++ development.• I myself am partial to Netbeans.
• We’ll be using Visual Studio in the labs.• Start Visual Studio• Create a new C++ Project
• A Win32 Console Project
Settings• In Application Settings
• Application type should be Console Application• Check the Empty Project checkbox
• Or you’ll end up with lots of stuff you don’t want.
• Click finish
• Add a source file.• Go to the solution explorer• Right click on the project file• Add -> Add New Item• The template should be a C++ (cpp file)• Enter the filename (say, main.cpp) to get a blank file.
C++ Syntax• Basic structures of C++ are very similar to Java.
• They are both c-type languages.
• The following are almost syntactically identical:• If statements• Switch statements• Variable declarations• For loops• While loops
Some Minor Differences• While the syntax is very similar (and thus we won’t spend
a lot of time discussing it), there are some minor differences.
• C++ will interpret any non-zero value as true in an if or continuation condition:
int blah;
blah = 1;
if (blah) { cout << "What Up!" << endl; }
Some Minor Differences• Strings in C++ are declared in lower case:
string bing;• Standard decimal data type is a float.
• Not a double.
• Booleans known as bool• Work the same way.
• Non null values in conditionals evaluate as true.• They don’t have to explicitly be true or false conditions
Some Major Differences• Functions in C++ often need to be prototyped.
• This means you provide a little ‘hint’ for the compiler by stating the function signature at the top of the file.
#include <iostream>using namespace std;void print_message (string);
int main() { print_message ("bing"); return 1;}
void print_message (string txt) { cout << txt << endl;}
Some Major Differences• C++ programs make constant use of pointers.
• These are references to areas of memory rather than discreet values.
• Java does this too for non-primitive data types.• It handles it automatically.
• C++ requires you to explicitly manage pointer references yourself.• Very powerful, but also an easy way to mess up a program!
• We’ll talk about pointers towards the end of this lecture.
C++ File Structure• The code in a C++ program is usually broken up into two
parts.• A header file (with the suffix .h) which contains function prototypes
and preprocessor directives.• A source code file (cpp) which contains the code statements.
• A header file should not contain code.• A source file can (and sometimes should) contain
prototypes and directives.
The Preprocessor• Perhaps the most powerful new feature you will instantly
encounter is the preprocessor.• As indicated previously, it takes on the form of a powerful,
context sensitive search and replace routine.• The two most common directives are #include and
#define.• #include we have already seen
The Preprocessor• #define allows you to create a token that gets replaced
with something during the first runtime pass.• In C++, these get used in the same way as static consts in a java
class.
• For example, in our header file we might declare the following:
#define NAME“michael”
The Preprocessor• Whenever we compile a program, the compiler does a
pass over our code with the preprocessor.• Every time it sees the token NAME it will replace it with
the string literal “michael”.• This allows for constant values to be set in one place and
made available to entire programs provided they #include our header file.
The Preprocessor• This occurs before any C++ syntax checking in the
compiler.• You can introduce syntax errors this way.
• Some directives allow for conditional inclusions• For example, the #ifdef directive sets a section of directives to be
contingent on a certain token being defined.• That range is ended with an #endif• #else can be used, as in an if-else structure.• #undef can be used to undefine previous defines.
The Preprocessor#include <iostream>
#define TESTING 1
#ifdef TESTING#define TEXT "this is a test"#else#define TEXT "this is not a test"#endif
using namespace std;
void print_message (string);
int main() { print_message (TEXT); return 1;}
void print_message (string txt) { cout << txt << endl;}
The Preprocessor• It’s not terribly important you can see why this is useful at
the moment.• You should recognise what is happening though, because the
preprocessor is one of the biggest differences in C++ programming.
• We will be making use of the preprocessor as necessary as we go through the module material.
Input in C++• Text input in C++ is extremely easy to do.
• Somewhat of a departure from how it is done in Java.
• The cin stream is used for this.• The >> operator is used to pull information out of a stream
• cin reading terminates whenever it finds a space.• It is thus fine for reading in single words and atomic data.
Input in C++#include <iostream>
using namespace std;
void print_message (int);
int main() {
int age; cout << "What is your age?" << endl; cin >> age;
print_message (age); return 1;}
void print_message (int txt) { cout << "Your age is " << txt << endl;}
Input in C++• For reading in lines of text with spaces, the getline
function is used instead.• This takes two parameters
• The input stream to use• The variable into which it should place the received information.
• It returns no value.• Often getting input to work properly is a vaguely black are.
• We will talk about why later.
Pointers• Pointers represent the biggest departure from C++.
• They take some getting used to, but become second nature before too long.
• I am making the assumption here that you understand (in general, if not in specifics) that you understand how memory works in a computer program.• Interrupt now if I’m wrong!
Pointers• In general, C++ passes primitive variables by value.
• Functions get a copy of the data, not the data itself.• This means if you change it in one function, it one impact on the
original declaration.• This is equivalent to what happens in Java.
• But Java gives us limited options for changing the way that works.
Pointers#include <iostream>
using namespace std;
void add_to_num (int);
int main() {
int num;
num = 10;
add_to_num (num);
cout << "Number is " << num << endl; return 1;}
void add_to_num (int num) { num = num + 1;}
Pointers• In C++, we have access to two powerful operators.
• &, which is the reference operator• You can literally think of this as a shorthand for ‘address of’
• *, which is the dereference operator• You can think of this as ‘value of’
• We can use this to specialise our variables.
Pointers#include <iostream>
using namespace std;
void add_to_num (int*);
int main() {
int num;
num = 10;
add_to_num (&num);
cout << "Number is " << num << endl; return 1;}
void add_to_num (int *num) { *num = *num + 1;}
Pointers• I only want to touch on this at the moment.
• We don’t need to go into too much depth at this point, we’ll return to the topic later when it actually starts to matter.
• The important thing is that you recognise these operators when you see them.• *num means ‘the value of the memory location pointed to by num’• &num means ‘the memory location where num resides’
Summary• C++, like Java, is a C-Type language.
• It has many similarities.• It has many differences.
• The key differences are:• the preprocessor• pointers• The lack of a pure OOP framework
• Over the coming weeks, we’ll learn more about all of these.