280 likes | 382 Views
C++ Language Fundamentals. Contents. Introduction to C++ Basic syntax rules Declaring and using variables. 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
E N D
Contents • Introduction to C++ • Basic syntax rules • Declaring and using variables 2
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 3
Setting the Scene • C++ is an object-oriented evolution of C • C dates back to 1972 • C++ was introduced in 1985, by BjarneStroustrup • 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 4
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! 5
The Standard C++ Library #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; 6 • 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 usingnamespace 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 usingnamespace statement to bring into scope
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) • endlmeans "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; } HelloWorld.cpp int main(intargc, char *argv[]) … 7
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) SomeLibrary.lib Account.obj Account.cpp MyApp.exe Bank.obj Bank.cpp Customer.obj Customer.cpp C/C++ standard library compilation linking 8
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 -oHello man g++ 9
Getting Input #include <iostream> #include <string> using namespace std; int main() { string name; intage; 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 • 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 10
Making Decisions #include <iostream> #include <cmath> using namespace std; intmain() { inta, 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 • Here's an example of making simple decisions 11
2. Basic Syntax Rules • Statements and expressions • Comments • Legal identifiers • Classes • Functions and methods 12
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 13
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 /** … … */ 14
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: 15
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 16
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() 17
3. Declaring and Using Variables • Variables • Constants • #define directives • C++ built-in types • Using integers • Using floating point variables • Using characters • Using booleans • Quiz 18
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; intyearsToRetirement = 20; 19
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: consttype CONSTANT_NAME = initialValue; const long SPEED_OF_LIGHT = 299792458; constint SECONDS_IN_MIN = 60; constint SECONDS_IN_HOUR = SECONDS_IN_MINUTE * 60; const string BEST_TEAM_IN_WALES = "Swansea City"; // 20
#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 MAX(a, b) (((a) > (b)) ? (a) : (b)) 21
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 22
Using Integers • Integers store whole numbers • C++ supports signed and unsignedints (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; intyearOfBirth = 1997; short goalDifference = -5; long favouriteColor = 0xFF000000; // Hexadecimal intbitMask = 0701; // Octal 23
Using Floating Point Variables • Floating point variables store fractional and large values • float holds a single-precision floating point number • doubleholds 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 . 24
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'; // Newline char cr = '\r'; // Carriage return char tab = '\t'; // Horizontal tab char nul= '\0'; // Null character (ASCII value 0) char bsl = '\\'; // Backslash char sqt = '\''; // Single quote char dqt = '\"'; // Double quote char aDec = 97; // Assign decimal value to char char aOct = '\141'; // Assign octal value to char char aHex = '\x97'; // Assign hexadecimal value to char wchar_tunicodeChar = L'A'; 25
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; interrorCount; … bool isBad = errorCount; // If errorCount is non-zero, isBad is true. cout << isBad; // Outputs true or false. interrorCount; … if (errorCount) { … } // If errorCount is non-zero, it means "true". 26
Quiz • What does this code do? #include <iostream> #include <string> using namespace std; void main() { intswans, 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; } 27