Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ in 90 minutes.

Similar presentations


Presentation on theme: "C++ in 90 minutes."— Presentation transcript:

1 C++ in 90 minutes

2 Overview Introduction "Hello World!" Using the gcc compiler
Elements of C++: control structures A word on organising code Classes Using templates: the STL

3 Introduction C++: general-purpose programming language
Developed as enhancement of C free-form, compiled language statically typed multi-paradigm: imperative, object-oriented, meta

4 "Hello World!" Every command is terminated by a semicolon ";"
#include <iostream> // This is the Hello World program int main() { /* Print "Hello World" to the screen */ std::cout << "Hello World!" << std::endl; return 0; } Tell the compiler to use information from the „header“ file called „iostream“ This is a comment Main function, part of every program, returns an integer Braces define code block Return to OS Every command is terminated by a semicolon ";" Commands may span more than one line There may be several commands on one line Many whitespaces are optional

5 Using the gcc compiler g++ -o <outfile> {input files}
For example: g++ -o helloworld helloworld.cpp Further useful options: -c do not link executable, but only create object file g++ -c –o object1.o file1.cpp g++ -o program object1.o object2.o …

6 Declaring variables General syntax: [specifiers(s)] type var_name [= initial_value]; Examples: int i; float z = 1.3; const double pi = ; Variables do not need to be declared at the beginning of a function Good style: Declare where needed Initialise immediately, if possible

7 Native types NB: - These numbers are machine and compiler dependent!
type size (char) min max char: signed char: unsigned char: short: unsigned short: int: unsigned int: long: unsigned long: long long: unsigned long long: bool: float: e e+38 double: e e+308 long double: e e+4932 NB: - These numbers are machine and compiler dependent! - In most cases char has a size of 1 byte.

8 Operators add and assign, … += -= *= /= address of & dereference *
logical and, logical or, logical not && || ! less, less-or-equal, greater, … < <= > >= equal-to, not-equal-to == != assignment = increment, decrement ++ -- plus, minus, multiply, divide, modulus + - * / %

9 Arrays Create a static array of numbers: double myArray[5];
Access its components, first component is 0: myArray[0] = 4.0; myArray[1] = ; double sum = myArray[0] + myArray[1]; These arrays have a fixed size that must be known at compile time. More on dynamic arrays later

10 Some notes for C users Don't use standard C strings: char *mystring = “My words”; but: #include <string> std::string mystring = “My words”; Instead of C arrays int myArray[4]; use C++ vectors or lists: #include <vector> std::vector<int> myArray; Instead of malloc and free use new and delete

11 Loops Predefined number of iterations: for-loop for (initialisation; condition; increment) { commands; } Example: for (int i = 0; i < 5; ++i) { cout << i << endl; } The loop will be continued while the condition is true

12 Loops Loop with initial condition: while while (condition) { commands; } Example: unsigned int answer = 99; while (answer > 5) { cout << "Enter a number <= 5: "; cin >> answer; }

13 Loops Loop with final condition: do { commands; } while (condition);
Example: unsigned int answer = 0; do { cout << "Enter a number: "; cin >> answer; } while (answer > 5);

14 Conditions Execute conditionally: if (condition) { commands; } else if (condition) { commands; } else { commands; } else if and else parts can be skipped

15 Conditions A condition is a boolean or integer expression
The if part is evaluated if the condition evaluates to true or is non-zero Examples: if (mynumber == 0) if (mybool) or if (!mybool) if ((n > 2) && (n < 5)) if (mynumber)

16 Functions Define a function: return_type name(arguments) { commands; }
Examples: int foo() { … } int foo(double x) { … } void foo(float j) { … } Return from function: return; or return x;

17 Functions Use a function: void do_initialisation() { ... } int main() { do_initialisation(); } Functions need to be declared before they can be used

18 Passing arguments to functions
Call by value: void foo(int bar) { ... } int x = 3; foo(3); // good foo(x); // good bar is a new local variable x or 3 are copied to bar Changing bar does not affect x

19 Passing arguments to functions
Call by reference: void foo(int &bar) { ... } int x = 3; foo(3); // no good foo(x); // good bar only contains a reference to what is passed to foo Changing bar will affect x Make sure that arguments remain unchanged, use a const reference: void foo(const int &bar) { ... }

20 Passing arguments to functions
Functions can have default arguments: void foo(int bar = 3) { ... } Then one can call foo(); or foo(4); Arguments with default values must be the last ones No named parameters: void foo(int b=2, int c=3) { ... } Call: foo(2, 4);

21 Overloading functions
Functions accepting different arguments can have the same name int foo(int x) { ... } double foo(double x) { ... } The compiler will select the best-matching function Identical arguments but different return types are not possible: int foo(int x) { ... } double foo(int x) { ... } // error

22 Pointers A pointer is a variable that contains the address of another variable Declare a pointer: double my_number = 6; double *my_ptr = &my_number; Access the value behind a pointer: cout << *my_ptr << endl; prints 6 on the screen cout << my_ptr << endl; prints something like 0x9a2290

23 Heap and stack Variables are stored on the stack
The stack size needs to be determined during compilation Additional memory can be requested from the OS with the operator new: int *var = new int; int *arr = new int[nitems]; This memory needs to be freed when x is no longer needed: delete var; delete[] arr;

24 Program organisation Split larger projects into several source files
Put declarations of functions and classes into header files (.h): double foo(int bar); Put definitions into source file (.cxx, .cpp, .C): #include "my_header.h" double foo(int bar) { do_something(); }

25 Namespaces Logical units of code can be grouped into namespaces: namespace Foo { void bar(int i); const double pi = ; } Then use: x = Foo::pi * r * r; Or: using namespace Foo; x = pi * r * r;

26 Creating a class Minimal class: class Foo {};
Add some data: class Foo { private: // only visible inside Foo int bar; }; // <-- semicolon, important! Add functions: class Foo { public: // visible from outside Foo int GetBar() { return bar; } private: // only visible inside Foo int bar; };

27 Using a class Create an instance of a class: Foo thing; // just like creating a variable Use the class, call a member function: int myvar = thing.GetBar(); Cannot use private members: int myvar = thing.bar; Compiler error: classes.cpp: In function 'int main()': classes.cpp:7: error: 'int Foo::bar' is private classes.cpp:13: error: within this context

28 Using a class Pointer to an object: Foo *myFoo = new Foo;
Access a member: dereference first int myBar = (*myFoo).GetBar(); Better: use the -> operator int myBar = myFoo->GetBar(); Both are equivalent

29 Splitting declaration and definition
Class declaration (goes into the header file): class Foo { public: int GetBar(); void SetBar(int x); private: int bar; }; Definitions go into the implementation file: int Foo::GetBar() { return bar; } void Foo::SetBar(int x) { bar = x; }

30 Constructors Constructors are used to initialise an object when it is created A constructor is a member function that has the same name as the class but no return type A constructor can take arguments and can be overloaded: class Foo { public: Foo() { ... } // default constructor Foo(int x) { ... } };

31 Constructors Constructors cannot be called directly
Creating a variable calls the default constructor: Foo bar; Use special constructor: Foo bar(5); Foo bar = Foo(5);

32 Constructors Initialisation of class members: Initialisation lists
Example: class Foo { public: Foo() : bar1(2.1415), bar2(3) { ... } private: double bar1; int bar2; };

33 Destructors Deleting class frees memory required by member
However: Dynamically allocated memory is not freed Use custom destructor A Destructor is a function of the form ~Classname(); No arguments Cannot be overloaded Cannot be called directly

34 Class hierarchies Derived classes: class base_class { // constructors and // some class members }; class derived : public base_class { // some class members };

35 Class hierarchies The derived class inherits all members from the base class But: it does not inherit constructors and destructors The derived class can override members of the base class derived_class base_class

36 Templates The C++ Standard Library utilises templates to be more generic Example: A class that respresents an array of objects For different types of objects the same code would need to be duplicated Template: write generic code and let the compiler do the duplication Templates are one of the most powerful features of C++

37 Templates Use a template: #include <vector> std::vector<double> myvector; Now use myvector just as any other object Useful templates in std lib: vector: array, fast acces, slow modification list: linked list, slow acces, fast modification map: associated list, tree structure Templates with more than one parameter: map<int, string> myMap;

38 Iterators Used to iterate through list-like objects
Special kind of pointer Two types exist: iterator and const_iterator For more on iterators see code example: stlvector.cpp

39 Finally ... This is just a basic introduction to a few features of C++
No-one can become an expert in C++ within 90 minutes Now start writing your own programs and learn by using the language This presentation and all examples can be found at

40 Some useful links English tutorial on C++: Nice (German) online book on C++: entwicklung.de/cpplinux/cpp_main/cpp_main.html References on the C++ standard library: Advanced discussions of C++ features:


Download ppt "C++ in 90 minutes."

Similar presentations


Ads by Google