28
C++ Language Fundamentals

C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

Embed Size (px)

Citation preview

Page 1: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

C++ Language Fundamentals

Page 2: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

2

Contents

1. Introduction to C++

2. Basic syntax rules

3. Declaring and using variables

Page 3: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

3

1. Introduction to C++

Setting the scene Differences between C++ and Java The Standard C++ library Hello world! Compiling and linking a C++ program Getting input Making decisions

Page 4: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

4

Setting the Scene

C++ is an object-oriented evolution of C• C dates back to 1972• C++ was introduced in 1985, by Bjarne Stroustrup• C++ is now an ANSI standard

Characteristics of C++• Object-oriented, i.e. supports classes, inheritance,

polymorphism• Strongly typed at compile-time• Supports generic programming via templates, e.g. list<int>

Uses of C++ are extremely widespread• E.g. middle-tier business rules in a distributed application• E.g. low-level process control

Page 5: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

5

Differences between C++ and Java

C++ is compiled directly to machine code• No concept of "byte codes" (like you have in Java)• So you must re-compile for each target platform

C++ applications run directly on the O/S• No virtual machine between C++ and the O/S• No garbage collection - you must de-allocate objects

yourself• No dynamic class loading - you must link all object files

into a .exe• Direct access to memory via pointers - powerful but

dangerous

The C++ Standard Template Library (STL) is extremely limited compared to the Java SE library• STL has string, IO, and collection classes• But STL doesn't have GUI / database / network /

multithreading!

Page 6: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

6

The Standard C++ Library

The standard C++ lib incorporates the standard C lib• You include header files such as <cstdio>, <cmath>, etc.• Declarations are nested in the std namespace, so you can

use a using namespace statement to bring into scope

The standard C++ lib also defines standard C++ classes• You include header files such as <iostream>, <vector>,

etc.• Declarations are nested in the std namespace, so you can

use a using namespace statement to bring into scope

#include <cstdio> // #include is a pre-processor directive to include a header file.#include <cmath>

using namespace std; // Allows unqualified access to standard C++ functions and classes.

#include <cstdio> // #include is a pre-processor directive to include a header file.#include <cmath>

using namespace std; // Allows unqualified access to standard C++ functions and classes.

#include <iostream>#include <vector>

using namespace std;

#include <iostream>#include <vector>

using namespace std;

Page 7: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

7

Hello World!

Here's a traditional "Hello World" program in C++• main() is a global function, the entry-point in a C++

application• cout outputs a message to the console (there's also cin, cerr)

• endl means "new line"

You can also declare main() as follows• Provides access to command-line arguments

// Include the standard header file that declares cout and endl.#include <iostream>

// Allow easy access to cout and endl, in the std namespace.using namespace std;

int main(){ cout << "Hello world!" << endl; return 0;}

// Include the standard header file that declares cout and endl.#include <iostream>

// Allow easy access to cout and endl, in the std namespace.using namespace std;

int main(){ cout << "Hello world!" << endl; return 0;} HelloWorld.cpp

int main(int argc, char *argv[]) …int main(int argc, char *argv[]) …

Page 8: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

8

Compiling/Linking a C++ Program (1 of 2)

C++ is a compiled language• Comprises source-code files (e.g. Account.cpp - you can

name files anything you like!)• Source-code files are compiled to object files (e.g. Account.obj)

• Object files are linked together, along with library files perhaps, to create executable files (e.g. MyApp.exe)

Account.cpp

Bank.cpp

Customer.cpp

Account.obj

Bank.obj

Customer.obj

compilation

MyApp.exe

linking

SomeLibrary.lib

C/C++ standard library

Page 9: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

9

Compiling/Linking a C++ Program (2 of 2)

For example, to compile/link a C++ program in Linux:• You can use the g++ command-line compiler/linker• Use the -o option to specify the name of the executable

output file

Here's an example...• Compiles HelloWorld.cpp to an object file• Links the object file with the standard C++ library, to

create an executable output file named Hello

If you want more info about g++ command options:

g++ HelloWorld.cpp -oHellog++ HelloWorld.cpp -oHello

man g++man g++

Page 10: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

Here's an example of how to get input from the console

• string is a standard C++ class, defined in the <string> header

• cin inputs a value (e.g. a string or an int) from the console

Getting Input

10

#include <iostream>#include <string>

using namespace std;

int main(){ string name; int age;

cout << "Hi, what's your name? "; cin >> name;

cout << "How old are you? "; cin >> age;

cout << name << ", on your next birthday you'll be " << age + 1 << endl;

return 0;}

#include <iostream>#include <string>

using namespace std;

int main(){ string name; int age;

cout << "Hi, what's your name? "; cin >> name;

cout << "How old are you? "; cin >> age;

cout << name << ", on your next birthday you'll be " << age + 1 << endl;

return 0;} PersonDetails.cpp

Page 11: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

Here's an example of making simple decisions

Making Decisions

11

#include <iostream>#include <cmath>

using namespace std;

int main(){ int a, b, c;

cout << "Enter the coefficient of x-squared, x, and units: "; cin >> a >> b >> c;

double disc = (b * b) - (4 * a * c); if (disc < 0) { cerr << "Roots are imaginary " << endl; } else { double root1 = (-a + sqrt(disc)) / 2 * a; double root2 = (-a - sqrt(disc)) / 2 * a; cout << "Roots are " << root1 << " and " << root2 << endl; } return 0;}

#include <iostream>#include <cmath>

using namespace std;

int main(){ int a, b, c;

cout << "Enter the coefficient of x-squared, x, and units: "; cin >> a >> b >> c;

double disc = (b * b) - (4 * a * c); if (disc < 0) { cerr << "Roots are imaginary " << endl; } else { double root1 = (-a + sqrt(disc)) / 2 * a; double root2 = (-a - sqrt(disc)) / 2 * a; cout << "Roots are " << root1 << " and " << root2 << endl; } return 0;} MakingDecisions.cpp

Page 12: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

12

2. Basic Syntax Rules

Statements and expressions Comments Legal identifiers Classes Functions and methods

Page 13: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

13

Statements and Expressions

C++ code comprises statements• C++ statements end with a semi-colon• You can group related statements into a block, by using {}

C++ code is free-format• But you should use indentation to indicate logical structure

An expression is part of a statement. For example:• a+b• a == b

Page 14: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

14

Comments

Single-line comment• Use //• Remainder of line is a comment

Block comment• Use /* … … */• Useful for larger comments, e.g. at the start of an

algorithm

Note:• No concept of JavaDoc-style comments• So you can't use /** … … */

Page 15: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

15

Legal Identifiers

Identifiers (names for classes, methods, variables, etc.):• Must start with a letter or _• Thereafter, can contain letters, numbers, and _• Are case sensitive

Keywords:

Page 16: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

16

Classes

You can define classes (nouns) in any source file• You don't have to define classes in a file with the same

name• … although many developers do like to do this

Standard C++ classes are all lowercase• E.g. string• E.g. list<T>• E.g. file

Some developers like to use capitalization (like in Java)• E.g. BankAccount• E.g. Bank• E.g. Customer

Page 17: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

17

Functions and Methods

C++ is based on C (this is an important pragmatic point)• So C++ supports global functions • i.e. you don't have to define everything in a class!

C++ offers many global functions from its C heritage, and are all lowercase• E.g. sqrt()• E.g. max()• E.g. printf()

Some developers like to use capitalization• E.g. CalcInterest()• E.g. TransferFunds()

Page 18: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

18

3. Declaring and Using Variables

Variables Constants #define directives C++ built-in types Using integers Using floating point variables Using characters Using booleans Quiz

Page 19: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

19

Variables

All applications use variables• A variable has a name, a type, and a value• Note, all variables in C++ are "garbage" until you assign a

value!!!

General syntax:

Example:

A variable also has a scope:• Block scope• Method scope• Object scope• Class scope

type variableName = optionalInitialValue;type variableName = optionalInitialValue;

int yearsToRetirement = 20;int yearsToRetirement = 20;

Page 20: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

20

Constants

A constant is a fixed "variable"• Use the const keyword (similar to final variables in Java)• Make sure the constant has a known initial value• The compiler will ensure you don't modify the constant

thereafter

General syntax:

Example:

const type CONSTANT_NAME = initialValue;const type CONSTANT_NAME = initialValue;

const long SPEED_OF_LIGHT = 299792458;const int SECONDS_IN_MIN = 60;const int SECONDS_IN_HOUR = SECONDS_IN_MINUTE * 60;const string BEST_TEAM_IN_WALES = "Swansea City"; //

const long SPEED_OF_LIGHT = 299792458;const int SECONDS_IN_MIN = 60;const int SECONDS_IN_HOUR = SECONDS_IN_MINUTE * 60;const string BEST_TEAM_IN_WALES = "Swansea City"; //

Page 21: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

21

#define Directives

C++ code can use #define directives (originated in C)• Anything that starts with # is a pre-processor directive• Expanded (prior to compilation) by the pre-processor

Examples in the <climits> standard C++ header file:

#define directives can take parameters• These are known as macros… good or bad?

#define INT_MIN -32767#define INT_MAX 32767#define UINT_MAX 65535…

#define INT_MIN -32767#define INT_MAX 32767#define UINT_MAX 65535…

#define MAX(a, b) (((a) > (b)) ? (a) : (b))#define MAX(a, b) (((a) > (b)) ? (a) : (b))

Page 22: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

22

C++ Built-in Types

Here is the full set of built-in types in C++:• Note: the size/range details vary, based on compiler and

platform

Page 23: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

23

Using Integers

Integers store whole numbers• C++ supports signed and unsigned ints (default is signed)

• Absolute size of these types is platform-dependent!• You can use decimal, hex, or octal notation

Examples:int x, y, z;short age;long population;unsigned short goalsScored;

int yearOfBirth = 1997; short goalDifference = -5; long favouriteColor = 0xFF000000; // Hexadecimalint bitMask = 0701; // Octal

int x, y, z;short age;long population;unsigned short goalsScored;

int yearOfBirth = 1997; short goalDifference = -5; long favouriteColor = 0xFF000000; // Hexadecimalint bitMask = 0701; // Octal

Page 24: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

24

Using Floating Point Variables

Floating point variables store fractional and large values• float holds a single-precision floating point number • double holds a double-precision floating point number

Should you use float or double?• Use double in most cases (all the C++ APIs do)• … unless memory is critical

Examples:double pi = 3.14159;double c = 2.99E8; // 2.99 x 108

double e = -1.602E-19; // -1.602 x 10-19

float height = 1.58F; // The F (or f) suffix means "float", i.e. not "double".float weight = 58.5F; // Ditto .

double pi = 3.14159;double c = 2.99E8; // 2.99 x 108

double e = -1.602E-19; // -1.602 x 10-19

float height = 1.58F; // The F (or f) suffix means "float", i.e. not "double".float weight = 58.5F; // Ditto .

Page 25: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

25

Using Characters

Characters are single-byte values (not Unicode!)• Enclose character value in single quotes

Examples:

If you want to store Unicode characters, use wchar_t

char myInitial = 'A';

char nl = '\n'; // Newlinechar cr = '\r'; // Carriage returnchar tab = '\t'; // Horizontal tabchar nul = '\0'; // Null character (ASCII value 0)char bsl = '\\'; // Backslashchar sqt = '\''; // Single quotechar dqt = '\"'; // Double quote

char aDec = 97; // Assign decimal value to charchar aOct = '\141'; // Assign octal value to charchar aHex = '\x97'; // Assign hexadecimal value to char

char myInitial = 'A';

char nl = '\n'; // Newlinechar cr = '\r'; // Carriage returnchar tab = '\t'; // Horizontal tabchar nul = '\0'; // Null character (ASCII value 0)char bsl = '\\'; // Backslashchar sqt = '\''; // Single quotechar dqt = '\"'; // Double quote

char aDec = 97; // Assign decimal value to charchar aOct = '\141'; // Assign octal value to charchar aHex = '\x97'; // Assign hexadecimal value to char

wchar_t unicodeChar = L'A';wchar_t unicodeChar = L'A';

Page 26: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

26

Using Booleans

bool variables are true/false values

C++ supports automatic conversions to bool• Any non-zero value implicitly means truth

C++ allows non-booleans in test conditions• Quite different than Java!

bool isWelsh = true;bool canSing = false;

bool isWelsh = true;bool canSing = false;

int errorCount;…bool isBad = errorCount; // If errorCount is non-zero, isBad is true.cout << isBad; // Outputs true or false.

int errorCount;…bool isBad = errorCount; // If errorCount is non-zero, isBad is true.cout << isBad; // Outputs true or false.

int errorCount;…if (errorCount) { … } // If errorCount is non-zero, it means "true".

int errorCount;…if (errorCount) { … } // If errorCount is non-zero, it means "true".

Page 27: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

27

Quiz

What does this code do?#include <iostream>#include <string>

using namespace std;

void main(){ int swans, bloobs;

cout << "Goals for Swans: "; cin >> swans;

cout << "Goals for Cardiff: "; cin >> bloobs;

cout << "Swansea " << swans << "-" << bloobs << " Cardiff" << endl;

cout << "Press ENTER to continue dude..."; cin.ignore(256, '\n'); cin.peek();

cout << "I'm outta here!" << endl;}

#include <iostream>#include <string>

using namespace std;

void main(){ int swans, bloobs;

cout << "Goals for Swans: "; cin >> swans;

cout << "Goals for Cardiff: "; cin >> bloobs;

cout << "Swansea " << swans << "-" << bloobs << " Cardiff" << endl;

cout << "Press ENTER to continue dude..."; cin.ignore(256, '\n'); cin.peek();

cout << "I'm outta here!" << endl;}

Page 28: C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

28

Any Questions?