Introduction Basic changes Objects Homework 5. C++ Jan Dugacek September 11, 2017 Jan Dugacek 5. C++ Introduction Basic changes Objects Homework ontents Introduction Basic changes • nullptr • Shorter struct 9 Reference • Printing • Including C libraries • Functions with same names • Allocating 9 Exercises Objects 9 struct expanded • Constructors and destructors 9 Const correctness 9 Operator overloading • Encapsulation 9 class 9 friend 9 Exercises 9 std::string Homework < □ ► 1= <\(y Jan Dugäcek 5. C++ Introduction Basic changes Objects Homework • You know most of C now • Many trivial things are quite hard to do in C • C++ allows to do these things more practically o Practicality often comes at the cost of execution speed, but not necessarily • To remember the keyword easier: https://www.youtube.com/watch?v=c3zLTpDbyDc Jan Dugacek 5. C++ Introduction Basic changes Objects Homework nullptr Shorter struct Reference Printing Including C libraries Functions with same names Allocating float* num = nullptr; • nullptr, is used in the same way as NULL, but it cannot be accidentally assigned as number 0 • It is good for avoiding mistakes Jan Dugäcek 5. C++ orter struct Introduction Basic changes Objects Homework nullptr Shorter struct Reference Printing Including C libraries Functions with same names Allocating struct stuff { i n t index; char a bbrev[4]; }; stuff a = {3, "axe"}; 9 You don't have the use the struct keyword before the type name Jan Dugäcek 5. C++ Introduction Basic changes Objects Homework nullptr Shorter struct Reference Printing Including C libraries Functions with same names Allocating Exercises VO i d } //■■ i n crem ent ( i n t& a) { a++; i n t a = 2 ; increment(a); i n t& b = a ; not assign ment Reference is similar to pointer, but it's automatically dereferenced every time it is used It must be initialised when created and can never be changed (it would change the variable it's initialised to) Any change to the reference will change the variable it points to, obtaining its address will obtain the address of the variable it points to It is sometimes practical to have a pointer with limited abilities, but the side effect of functions that accept reference arguments is not visible o1 1= ^) <\(y Ján Dugácek 5. C++ Introduction Basic changes Objects Homework nullptr Shorter struct Reference Printing Including C libraries Functions with same names Allocating ^include \\... i n t a = 2 ; std : : cout « "Value of a " « a « std : : end I ; • More comfortable than printf(), but can't do all that printf() can do 9 The printing functions called are chosen in compile time according to the type of the variable • If you write std: :end instead of std: :endl, you will get a 1000 lines long error report (if you get an error report that long, check for this error) 1= <\(y Jan Dugäcek 5. C++ Introduction Basic changes Objects Homework nullptr Shorter struct Reference Printing Including C libraries Functions with same names Allocating Exercises i] a C library functions are not useless in C++ • While you may use #include , it's better to omit the .h suffix and add a c prefix, writing #include • If you include the C libraries that way, you don't have to use -lmath compiler arguments and such Jan Dugäcek 5. C++ nullptr Shorter struct Reference Printing Including C libraries Functions with same names Allocating unctions with same names void identify (int a) { std :: cout « "A is an integer" « std :: endI ; } void identify(fIoat a) { std : : cout « "A is a float " « std : : end I ; } • The functions have different names after compilation, containing also the types of arguments • The compiler chooses which function is called (C++ is still statically typed language, the types are fixed but can be deduced by compiler) o Although float can be implicitly converted to int, the compiler picks the function whose type is closer (or reports ambiguity) < □ ► < s ► < i ► < i ► Jan Dugäcek 5. C++ Introduction Basic changes Objects Homework nullptr Shorter struct Reference Printing Including C libraries Functions with same names Allocating i n t * i n t * i n t * a = new b = new c = new delete a ; d e I ete [ ] c ; int; // Allocates an integer i nt (2); Al locates an int [ 2 ] ; Allocates ar array I nstead of free // Use this to free arrays • You can still use mallocO, but it's less practica o delete what was allocated with new, free() what was allocated with mallocO Jan Dugäcek 5. C++ Introduction Basic changes Objects Homework nullptr Shorter struct Reference Printing Including C libraries Functions with same names Allocating O Pick a program from previous exercises and rewrite it to use the C++ habits Q Pick another program from previous exercises and rewrite it to use the C++ habits Terminate files with .cpp, compile C++ using g++ main.cpp -std=c++ll -o main, arguments are the same. Jan Dugäcek 5. C++ Introduction Basic changes Objects Homework struct expanded struct expanded Constructors and destructors Const correctness Operator overloading Encapsulation class friend Exercises std::string struct }; counter { i n t count_ ; void increment () { count_++; } counter a = { 0 }; a. increment (); • struct can have functions (called methods) that are attached to them and can access the variables they contain as local variables • To avoid mistaking parts of the struct with local variables, they should have a common prefix or suffix • Methods are internally regular functions that use the pointer to the class as first argument, they are not a part of the struct < = ► < = 1= ^) <\(y Jan Dugacek 5. C++ Introduction Basic changes Objects Homework Constructors and destructors struct expanded Constructors and destructors Const correctness Operator overloading Encapsulation class friend Exercises std::string struct poi nterGuard { i n t * poi nter_ ; poi nterGuard(int* pointer) ~poi nterG ua rd() { delete pointer_; } }; vo i d } // doStuff { int* pointer = new int(4); pointerGuard gua rd ( po i n te r ); guard expires , destructor is ca poi nter_ ( po i n te r) { } ed Function with same name as the struct and no return value is a constructor, it is called when it is created Function named after the struct but with the "prefix and no arguments is a destructor, it's called when the object is deleted or expires 1= ^) <\(y Jan Dugacek 5. C++ Introduction Basic changes Objects Homework struct expanded Constructors and destructors Const correctness Operator overloading Encapsulation class friend Exercises std::string onst correctness struct }; cmplx { float real float float } imag ; abs() const { retu rn sq rt(reaI real + imag * imag); const cmplx a = {2, 3}; float ab = a.a bs(); • Only methods declared as const may be called on objects declared as const • Methods declared as const may not modify attributes (unless these attributes have the mutable modifier) 1= <\(y Jan Dugacek 5. C++ Introduction Basic changes Objects Homework Operator overloading struct expanded Constructors and destructors Const correctness Operator overloading Encapsulation class friend Exercises std::string struct counter { i n t count_ ; counter () : count_(0) {} void o pe r a to r++( i n t unused) { count_++; } }; counter a++; // operator++() without argument would be for H—ha • You can define operations that can be done with the object using operators • If the operations is not unary, the method accepts an argument that is the other operand Jan Dugäcek 5. C++ Introduction Basic changes Objects Homework struct expanded Constructors and destructors Const correctness Operator overloading Encapsulation class friend Exercises std::string perator overloading struct matrix_3x3 { float val_[3][3]; bool operator= (matrix_3x3& other) { for (int i = 0; i<3; i++) for (int j = 0; j < 3; j++) if (val_[i][j]! = other.val_[i][j]) return false; return true; } void operator+= (matrix_3x3& other); matrix_3x3 operator* (float m); elsewhere matrix_3x3 operator* (vector_3& v); matrix_3x3 operator* (matrix_3x3& other); }; Jan Dugacek 5. C++ Introduction Basic changes Objects Homework struct expanded Constructors and destructors Const correctness Operator overloading Encapsulation class friend Exercises std::string struct counter { public : counter () count_(0) {} void o pe r a to r++( i n t unused) { count int getCount() { return count_ ; } _++; } private int cou nt }; To prevent mistakes, it is possible to make some content unavailable unless accessed from the right place Anything behind public: is available from everywhere, anything behind private: is available only from methods of that object type and anything behind protected: is available only for methods of that object It can be circumvented by changing the type to something with the same memory layout, but this is to prevent mistakes^nip^ tpjpr^egt hacking Jan Dugacek 5. C++ Introduction Basic changes Objects Homework class struct expanded Constructors and destructors Const correctness Operator overloading Encapsulation class friend Exercises std::string class counter { int cou nt public : counter () count_(0) {} void o pe r a to r++( i n t unused) { count int getCount() { return count_ ; } _++; } 9 In struct or union, everything is public until explicitly set, which is consistent with C and used for smaller objects in C++ 9 class is totally like struct, but it has everything private until a change (everything private is quite useless) • The variable types of struct and class are called classes, initialised variables in memory are called objects Jan Dugacek 5. C++ Introduction Basic changes Objects Homework struct expanded Constructors and destructors Const correctness Operator overloading Encapsulation class friend Exercises std::string class }; counter { i n t count_ ; friend void i ncrementCou nt ( cou nter& a); void i ncrementCou nt ( cou nter& a) { a . count_++; if (a . count_ % 10) { std : : cout « "Ten counts } } c a I « std : : e n d I • Any function or class declared as friend of some class, allowing it to access all its member variables • Friendship is not mutual (even) in programming 1= <\(y Jan Dugacek 5. C++ Introduction Basic changes Objects Homework struct expanded Constructors and destructors Const correctness Operator overloading Encapsulation class friend Exercises O Write a complex class that represents complex numbers and define operators for usual operations with them Q Write a class that acts like a str class, can be created from a char* with a constructor, has methods for appending other str, char* or char and obtaining its length (its content have to be extended if necessary) O Add to that class operators +, +=, ==, ! = Advanced: O Write classes matrix and vector that support operations +, - and * between each other and float and can be set to any dimension according to constructor arguments Jan Dugacek 5. C++ Introduction Basic changes Objects Homework struct expanded Constructors and destructors Const correctness Operator overloading Encapsulation class friend Exercises std::string std::string std : : string a ( " bla 11 ) ; std : : string b("42-l" ); std :: string c = a + b; // writes b I a 42 — 1 to c a += c; // appends c to a, resulting b I a b I a 4 2 a.append(".co" ); // appends to a, b I a bI a 4 2 a . push_back ( 'm ' ); // appends a character, b = a . substr (a . find ("bla") , 4); // picks blab • std: : string does most of the text things that is annoying to do with C 9 They are, however, often slower and not always practical • Use std: :getline(std: :cin, a); to read a line of input and save it into string a 9 It needs to include string Jan Dugacek 5. C++ Introduction Basic changes Objects Homework • Write a class that describes a function given by the values of its elements from 0 up to a value given in constructor (ideally a dynamically allocated array), elements are accessed with [] like in array, must have a method differentiate that replaces the array with its derivative (1 element shorter, needs resize) Advanced homework: • Your friend who is used to Python wants to use C++, but he is afraid of the static typing. Create a class named var with size 8 bytes, that can hold an integer, a float, a short string up to 7 characters, a pointer to a string of any size (for longer strings) or a pointer to an array of these variables (resizeable, expanded when writting behind end). Usual arithmetic should apply to all types as it would if the types were known, decided in runtime. See previous slides' section about union to see how to do it. enum types unsigned char { type car isPointer = 0, Jan Dugacek 5. C++