C89 vs C99 C11 Overview of the Lecture

Introduction to Object Oriented Part 1 – Brief Overview of C89 vs C99 vs C11 Programming in ++ C89 vs C99 Part I

C11 K. N. King: Appendix B Jan Faigl Part 2 – Object Oriented Programming (in C++) Part 1 – Brief Overview of C89 vs C99 vs Department of Computer Science Differences between C and C++ C11 Faculty of Electrical Engineering Czech Technical University in Prague Classes and Objects

Lecture 10 Constructor/Destructor BE5B99CPL – C Programming Language Example – Class Matrix

Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 1 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 2 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 3 / 49 C89 vs C99 C11 C89 vs C99 C11 C89 vs C99 C11 Differences between C89 and C99 Differences between C89 and C99 Differences between C89 and C99 – Additional Libraries

Bool type – C99 provides _Bool type and macros in stdbool.h Comments – In C99 we can use a line comment that begins with // Loops – C99 allows to declare control variable(s) in the first – macros false and true that denote the logical Identifiers – C89 requires compilers to remember the first 31 values 0 and 1, respectively characters vs. 63 characters in C99 statement of the Only the first 6 characters of names with external linkage are Arrays – C99 has – integer types with specified widths significant in C89 (no case sensitive) designated initializers and also allows – macros for input/output of types specified in In C99, it is the first 31 characters and case of letters matters to use variable-length arrays Keywords – 5 new keywords in C99: inline, , _Bool, Functions – one of the directly visible changes is – functions to perform mathematical operations on _Complex, and _Imaginary In C89, declarations must precede statements within a block. In complex numbers C99, it cam be mixed. Expressions – type-generic macros for easier call of functions Preprocessor – e.g., In C89, the results of / and % operators for a negative operand can defined in and be rounded either up or down. The sign of i % j for negative i or j C99 allows macros with a variable number of arguments depends on the implementation. C99 introduces __func__ macro which behaves as a string variable – provides access to floating-point status flags and In C99, the result is always truncated toward zero and the sign of that stores the name of the currently executing function control modes i i % j is the sign of . Input/Output – conversion specification for the *printf() and Further changes, e.g., see K. N. King: Appendix B *scanf() functions has been significantly changed in C99.

Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 5 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 6 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 7 / 49 C89 vs C99 C11 C89 vs C99 C11 C89 vs C99 C11 Overview of Changes in C11 – 1/2 Overview of Changes in C11 – 2/2 Generic Selection In C11, we can use a generic macros, i.e., macros with results that can be computed according to type of the pass variable (expression) support – Memory Alignment Control – _Alignas, _Alignof, and double f_i(int i) Bounds-checking functions – e.g., strcat_s() and strncpy_s() int main(void) aligned_alloc, { { gets() for reading a while line from the standard input has been return i + 1.0; int i = 10; Type-generic macros – _Generic keyword } double = 10.0; removed. double f_d(double d) printf("i=%d;d=%f\n", i, d); _Noreturn keyword as the function specifier to declare function It has been replaced by a safer version called gets_s() { return d - 1.0; printf("Results of fce(i)%f\n", does not return by executing return statement (but, e.g., rather In general, the bound-checking function aim to that the software written } fce(i)); in C11 can be more robust against security loopholes and malware attacks. printf("Results of fce(d)%f\n", longjmp)– #define fce(X) _Generic((X),\ fopen() interface has been extended for exclusive fce(d)); – multithreading support int: f_i,\ return EXIT_SUCCESS; create-and-open mode ("..x") that behaves as O_CREAT|O_EXCL double: f_d\ } – facilities for uninterruptible objects access in POSIX used for lock files )(X) lec10/demo-matrix.cc wx – create file for writing with exclusive access -std=c11 generic.c -o generic && ./generic Anonymous structs and unions, e.g., for nesting union as a i = 10; d = 10.000000 member of a struct w+x – create file for update with exclusive access Results of fce(i) 11.000000 Safer fopen_s() function has been also introduced Results of fce(d) 9.000000 A function is selected according to the type of variable during compilation. Static (parametric/compile-time) polymorphism Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 9 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 10 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 11 / 49 Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix

C C++ C C++ C was developed by Dennis Developed by Bjarne Stroustrup Concept of virtual functions is C++ offers the facility of using Ritchie (1969–1973) at AT&T in 1979 with C++’s predecessor “C not present in C virtual functions Part II Bell Labs with Classes” No operator overloading C++ allows operator overloading C is a procedural (aka C++ is procedural but also an Data can be easily accessed by Data can be put inside objects, Part 2 – Introduction to Object Oriented structural) programming object oriented programming other external functions which provides better data security language language C is a middle level language C++ is a high level language Programming C is a subset of C++ C++ can run most of C code The solution is achieved through C++ can model the whole solution C programs are divided into C++ programs are divided into a sequence of procedures or in terms of objects and that can modules and procedures classes and functions steps make the solution better organized

C is a function driven C++ is an object driven language C programs use top-down C++ programs use bottom-up language approach approach

Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 12 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 14 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 15 / 49 Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix

C C++ Objects Oriented Programming (OOP) C C++ Provides malloc() (calloc()) C++ provides new operator for Does not provide Namespaces are available for dynamic memory allocation memory allocation OOP is a way how to design a program to fulfill requirements is not easy Exception handling through Try and make the sources easy maintain. It provides free() function for It provides delete and (delete[]) in C and Catch block memory de-allocation operator for memory de-allocation Inheritance is not possible Inheritance is possible Abstraction – concepts (templates) are organized into classes Does not support for virtual and C++ supports virtual and friend Objects are instances of the classes Function overloading is not Function overloading is possible friend functions functions possible (i.e., functions with the same name) Encapsulation Polymorphism is not possible C++ offers polymorphism Functions are used for Objects (streams) can be use for Object has its state hidden and provides interface to communicate C supports only built-in data It supports both built-in and input/output, e.g., scanf() and input/output, e.g., std::cin and with other objects by sending messages (function/method calls) types user-defined data types printf() std::cout Inheritance Mapping between data and In C++ data and functions are Does not support reference Supports reference variables, Hierarchy (of concepts) with common (general) properties that are functions is difficult in C easily mapped through objects variables using & further specialized in the derived classes Does not support definition C++ supports definition C programs are saved in files C++ programs are saved in files Polymorphism (overloading) operators (overloading) of the operators with extension .c with extension .cc, .cxx or .cpp An object with some interface could replace another object with http://techwelkin.com/difference-between-c-and-c-plus-plus the same interface

Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 16 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 17 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 19 / 49 Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Class Object Structure Creating an Object – Class Constructor Describes a set of objects – it is a model of the objects and defines: A class instance (object) is created by calling a constructor to The value of the object is structured, i.e., it consists of particular initialize values of the instance variables Interface – parts that are accessible // header file - definition of values of the object data fields which can be of different Implicit/default one exists if not specified the class type Heterogeneous data structure unlike an array from outside public, protected, private class MyClass { The name of the constructor is identical to the name of the class public: Object is an abstraction of the memory where particular values are Class definition Class implementation Body – implementation of the interface /// public read only stored class MyClass { MyClass::MyClass(int i) : _i(i) (methods) that determine the ability of int getValue(void) const; public: { Data fields are called attributes or instance variables the objects of the class private: // constructor _ii = i * i; /// hidden data field Data fields have their names and can marked as hidden or MyClass(int i); _d = 0.0; Instance vs class methods /// it is object variable MyClass(int i, double d); } accessible in the class definition // overloading constructor Data Fields – attributes as basic and int myData; }; Following the encapsulation they are usually hidden private: MyClass::MyClass(int i, double d) : _i(i) complex data types and structures const int _i; { Object: int _ii; _ii = i * i; (objects) Object composition // source file - implementation Instance of the class – can be created as a variable declaration or double _d; _d = d; Instance variables – define the state of the of the methods }; } int MyClass::getValue(void) const by dynamic allocation using the new operator { object of the particular class { MyClass myObject(10);//create an object as an instance of MyClass Class variables – common for all instances return myData; Access to the attributes or methods is using . or -> (for pointers }// at the end of the block, the object is destroyed } of the particular class to an object) MyClass *myObject = new MyClass(20, 2.3);//dynamic object creation delete myObject;//dynamic object has to be explicitly destroyed Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 20 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 21 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 22 / 49 Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Relationship between Objects Access Modifiers Constructor and Destructor

Access modifiers allows to implement encapsulation (information Objects may contain other objects hidding) by specifying which class members are private and which Constructor provides the way how to initialize the object, i.e., are public: allocate resources Object aggregation / composition public: – any class can refer to the field or call the method Programming idiom – Resource acquisition is initialization (RAII) Class definition can be based on an existing class definition – so, protected: – only the current class and subclasses (derived Destructor is called at the end of the object life there is a relationship between classes classes) of this class have access to the field or method It is responsible for a proper cleanup of the object Base class (super class) and the derived class private: – only the current class has the access to the field or Releasing resources, e.g., freeing allocated memory, closing files The relationship is transfered to the respective objects as instances method of the classes Destructor is a method specified by a programmer similarly to a By that, we can cast objects of the derived class to class instances of ancestor Access constructor Modifier Class Derived Class “World” However, unlike constructor, only single destructor can be specified Objects communicate between each other using methods !!! public The name of the destructor is the same as the name of the class (interface) that is accessible to them !!  protected but it starts with the character as a prefix private !   ∼

Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 23 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 24 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 26 / 49 Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Constructor Overloading Example – Constructor Calling 1/3 Example – Constructor Calling 2/3 An example of constructor for creating an instance of the complex We can create a dedicated initialization method that is called from number different constructors Or we can utilize default values of the arguments that is combined In an object initialization, we may specify only real part or both with initializer list here the real and imaginary part class Complex { class Complex { class Complex { public: public: public: Complex(double r, double i) { init(r, i); } Complex(double r = 0.0, double i = 0.0) : re(r), im(i) {} Complex(double r) Complex(double r) { init(r, 0.0); } private: { Complex() { init(0.0, 0.0); } double re; re = r; double im; } private: }; Complex(double r, double i) void init(double r, double i) int main(void) { { re = r; re = r; { im = i; im = i; Complex c1; } } Complex c2(1.); ~Complex() {/* nothing to do in destructor*/} Complex c3(1., -1.); private: private: return 0; double re; double re; } double im; double im; }; }; Both constructors shared the duplicate code, which we like to avoid! Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 27 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 28 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 29 / 49 Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Example – Constructor Calling 3/3 Constructor Summary Class as an Extended Data Type with Encapsulation Data hidding is utilized to encapsulate implementation of matrix The name is identical to the class name class Matrix { Alternatively, in C++11, we can use delegating constructor The constructor does not have return value private: const int ROWS; Not even void const int COLS; class Complex { double *vals; public: Its execution can be prematurely terminated by calling return }; 1D array is utilized to have a continuous memory. Complex(double r, double i) It can have parameters similarly as any other method (function) { 2D dynamic array can be used in C++11. re = r; We can call other functions, but they should not rely on initialized In the example, it is shown im = i; How initialize and free required memory in constructor and } object that is being done in the constructor destructor Complex(double r) : Complex(r, 0.0) {} Constructor is usually public Complex() : Complex(0.0, 0.0) {} How to report an error using exception and try-catch statement (private) constructor can be used, e.g., for: How to use references private: double re; Classes with only class methods How to define a copy constructor double im; Prohibition to instantiate class How to define (overload) an operator for our class and objects }; Classes with only constants How to use C function and header files in C++ The so called singletons How to print to standard output and stream E.g., “object factories” How to define stream operator for output How to define assignment operator

Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 30 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 31 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 33 / 49 Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Example – Class Matrix – Constructor Example – Class Matrix – Hidding Data Fields Example – Class Matrix – Using Reference Primarily we aim to hide direct access to the particular data fields Class Matrix encapsulate dimension of the matrix The at() method can be used to fill the matrix randomly For dimensions we provide the so-called “accessor” methods The function is defined in , but in C++ we Dimensions are fixed for the entire life of the object (const) random() The methods are declared as const to assure they are read only prefer to include C libraries as methods and do not modify the object (compiler checks that) class Matrix { class Matrix { Matrix::Matrix(int rows, int cols) : Private method at() is utilized to have access to the particular public: public: ROWS(rows), COLS(cols) r c void fillRandom(void); Matrix(int rows, int cols); { cell at row and column private: ~Matrix(); vals = new double[ROWS * COLS]; inline is used to instruct compiler to avoid function call and rather private: inline double& at(int r, int c) const{ return vals[COLS * r + c]; } } put the function body directly at the calling place. }; const int ROWS; class Matrix { const int COLS; Matrix::~Matrix() public: #include double *vals; { }; delete[] vals; inline int rows(void) const{ return ROWS; }// const method cannot void Matrix::fillRandom(void) } inline int cols(void) const{ return COLS; }// modify the object { for(int r = 0; r < ROWS; ++r) { Notice, for simplicity we do not test validity of the matrix dimensions. private: for(int c = 0; c < COLS; ++c) { // returning reference to the variable allows to set the variable at(r, c) = (rand() % 100) / 10.0;// set vals[COLS * r + c] Constant data fields ROWS and COLS must be initialized in the // outside, it is like a pointer but automatically dereferenced } constructor, i.e., in the initializer list inline double& at(int r, int c) const } { } We should also preserve the order of the initialization as the variables return vals[COLS * r + c]; are defined } In this case, it is more straightforward to just fill 1D array of vals for }; i in 0..(ROWS * COLS). Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 34 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 35 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 36 / 49 Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Example – Class Matrix – Getters/Setters Example – Class Matrix – Exception Handling Example – Class Matrix – Printing the Matrix Access to particular cell class Matrix { The code where an exception can be raised is put into the of the matrix is provided public: We create a print() method to nicely print the matrix to the double getValueAt(int r, int c) const; try-catch block through the so-called void setValueAt(double v, int r, int c); standard output getter and setter methods }; The particular exception is specified in the catch by the class name Formatting is controlled by i/o stream manipulators defined in The methods are based on the private at() method but will throw We use the program standard output denoted as std::cout We can avoid std:: by using std; header file an exception if a cell out of ROWS and COLS would be requested #include #include Or just #include using std::cout; #include double Matrix::getValueAt(int r, int c) const #include"matrix.h" #include"matrix.h" { int main(void) if (r < 0 or r >= ROWS orc<0 or c >= COLS) { { void print(const Matrix& m) throw std::out_of_range("Out of range at Matrix::getValueAt"); int ret = 0; { } try{ std::cout << std::fixed << std::setprecision(1); return at(r, c); Matrix m1(3, 3); for(int r = 0; r < m.rows(); ++r) { } m1.setValueAt(10.5, 2, 3);// col 3 raises the exception for(int c = 0; c < m.cols(); ++c) { void Matrix::setValueAt(double v, int r, int c) std::cout << (c > 0 ?"":"") << std::setw(4); { m1.fillRandom(); std::cout << m.getValueAt(r, c); if (r < 0 or r >= ROWS orc<0 or c >= COLS) { } catch (std::out_of_range& e) { } std::cout <<"ERROR:" << e.what() << std::endl; std::cout << std::endl; throw std::out_of_range("Out of range at Matrix::setValueAt"); ret = -1 } } } } at(r, c) = v; return ret; } } lec10/demo-matrix.cc Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 37 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 38 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 39 / 49 Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Example – Class Matrix – Printing the Matrix Example – Class Matrix – Copy Constructor Example – Class Matrix – Dynamic Object Allocation Notice, the matrix variable m1 is not copied when it is passed to We can create a new instance of the object by the operator print() function because of passing reference We may overload the constructor to create an copy of the object new #include class Matrix { We may also combine dynamic allocation with the copy constructor #include public: #include"matrix.h" ... Notice, the access to the methods of the object using the pointer Matrix(const Matrix &m); to the object is by the operator void print(const Matrix& m); ... -> }; int main(void) ratrix m1(3, 3); { We create an exact copy of the matrix m1.fillRandom(); int ret = 0; std::cout <<"Matrix m1" << std::endl; try{ Matrix::Matrix(const Matrix &m) : ROWS(m.ROWS), COLS(m.COLS) print(m1); Matrix m1(3, 3); {// copy constructor m1.fillRandom(); vals = new double[ROWS * COLS]; Matrix *m2 = new Matrix(m1); std::cout <<"Matrix m1" << std::endl; for(int i = 0; i < ROWS * COLS; ++i) { Matrix *m3 = new Matrix(m2->rows(), m2->cols()); print(m1); vals[i] = m.vals[i]; std::cout << std::endl <<"Matrix m2" << std::endl; ... } print(*m2); } m3->fillRandom(); Example of the output std::cout << std::endl <<"Matrix m3" << std::endl; clang++ --pedantic matrix.cc demo-matrix.cc && ./a.out Notice, access to private fields is allowed within in the class print(*m3); Matrix m1 We are implementing the class, and thus we are aware what are the 1.3 9.7 9.8 internal data fields delete m2; 1.5 1.2 4.3 delete m3; 8.7 0.8 9.8 lec10/demo-matrix.cc lec10/matrix.h, lec10/matrix.cc, lec10/demo-matrix.cc Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 40 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 41 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 42 / 49 Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Example – Class Matrix – Sum Example – Class Matrix – Operator + Example – Class Matrix – Output Stream Operator The method to sum two matrices will return a new matrix In C++, we can define our own operators, e.g., + for sum of two A output stream operator << can be defined to pass Matrix class Matrix { public: matrices objects directly to the output stream Matrix sum(const Matrix &m2); It will be called like the sum() method #include class Matrix { ... }; } class Matrix { std::ostream& operator<<(std::ostream& out, const Matrix& m); The variable ret is passed using the copy constructor public: Matrix Matrix::sum(const Matrix &m2) Matrix sum(const Matrix &m2); It is defined outside the Matrix { Matrix operator+(const Matrix &m2); #include if (ROWS != m2.ROWS or COLS != m2.COLS) { } std::ostream& operator<<(std::ostream& out, const Matrix& m) throw std::invalid_argument("Matrix dimensions do not match at { Matrix::sum"); In our case, we can use the already implemented sum() method if (out) { } Matrix Matrix::operator+(const Matrix &m2) out << std::fixed << std::setprecision(1); Matrix ret(ROWS, COLS); { for(int r = 0; r < m.rows(); ++r) { for(int i = 0; i < ROWS * COLS; ++i) { return sum(m2); for(int c = 0; c < m.cols(); ++c) { ret.vals[i] = vals[i] + m2.vals[i]; } out << (c > 0 ?"":"") << std::setw(4); } out << m.getValueAt(r, c); return ret; We may also implement sum as addition to the particular matrix The new operator can be applied for the operands of the Matrix } } type like as to default types out << std::endl; The sum() method can be than used as any other method } Matrix m1(3, 3); Matrix m1(3,3); } m1.fillRandom(); m1.fillRandom(); “Outside” operator can be used in an output stream pipeline with other return out; data types. In this case, we can use just the public methods. But, if Matrix *m2 = new Matrix(m1); Matrix m2(m1), m3(m1 + m2);// use sum of m1 and m2 to init m3 } needed, we can declare the operator as a friend method to the class, Matrix m4 = m1.sum(*m2); print(m3); which can access the private fields. Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 43 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 44 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 45 / 49 Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Differences between C and C++ Classes and Objects Constructor/Destructor Example – Class Matrix Topics Discussed Example – Class Matrix – Example of Usage Example – Class Matrix – Assignment Operator = Having the stream operator we can use + directly in the output We can defined the assignment operator = std::cout <<"\nMatrix demo using operators" << std::endl; class Matrix { public: Matrix m1(2, 2); Matrix& operator=(const Matrix &m) Matrix m2(m1); { m1.fillRandom(); if(this != &m) {// to avoid overwriting itself m2.fillRandom(); if (ROWS != m.ROWS or COLS != m.COLS) { std::cout <<"Matrix m1" << std::endl << m1; throw std::out_of_range("Cannot assign matrix with std::cout <<"\nMatrix m2" << std::endl << m2; different dimensions"); Summary of the Lecture std::cout <<"\nMatrix m1+ m2" << std::endl << m1 + m2; } Example of the output operator for(int i = 0; i < ROWS * COLS; ++i) { Matrix demo using operators vals[i] = m.vals[i]; Matrix m1 } 0.8 3.1 } 2.2 4.6 return*this;// we return reference not a pointer } Matrix m2 }; // it can be then used as 0.4 2.3 Matrix m1(2,2), m2(2,2), m3(2,2); 3.3 7.2 m1.fillRandom(); m2.fillRandom(); Matrix m1 + m2 m3 = m1 + m2; 1.2 5.4 std::cout << m1 <<"+" << std::endl << m2 <<"=" << std::endl 5.5 11.8 lec10/demo-matrix.cc << m3 << std::endl; Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 46 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 47 / 49 Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 48 / 49 Topics Discussed Topics Discussed

C89 vs C99 vs C11 – a brief overview of the changes C vs C++ – a brief overview of differences Object oriented programming in C++ Introduction to OOP Classes and objects Constructor Examples of C++ constructs Overloading constructors References vs pointers Data hidding – getters/setters Exception handling Operator definition Stream based output

Next: OOP – Polymorphism, inheritance, and virtual methods.

Jan Faigl, 2016 BE5B99CPL – Lecture 10: OOP in C++ (Part 1) 49 / 49