Structures and Member Functions

Size: px
Start display at page:

Download "Structures and Member Functions"

Transcription

1 Structures and Member Functions We ve used structures before to enable us to group variables together to make our lives easier when programming C++ allows us to use functions within structures We create member functions to minimize the work we need to do to manipulate the data in our structures This will lead us up to C++ classes Classes 1

2 Structures and Member Functions Define a function inside the struct declaration Functions are inline Reference structure variables (i.e. re, im) directly in functions Use. or -> to access member functions struct _mycomplex double re, im; void print() cout << noshowpos << re << showpos << im << "j" << noshowpos; void setri(double a, double b) re = a; im = b; ; int main(void) struct _mycomplex c; c.setri(5,10); //c=5+10j c.print(); // print c 2 In this example, we can see the structure definition (double re, im) along with two functions (print and setri). These functions are considered to be inline, which means the compiler will use them as macros and place them completely where ever we called the code. Depending on the number of times we use the functions, our code can become very large. We can solve this potential problem using a different declaration. See the next slide. The print functions sets the output of the console such that when a number is printed, the sign is printed only when the number is negative (noshowpos do not show positive). Next, we output the real component (re) followed by setting the output to ALWAYS print the signs of a number (showpos show positive). We then print the imaginary part (im) followed by a j to tell use which part is the imaginary part. We end by setting the output back so that positive signs are not printed. Note that no new lines are printed, we have to do that elsewhere. The setri function accepts two arguments which we use to set the value of the complex variable. Our sample main function first declares a complex structure c and then sets the value to 5+10j. We do this using our setri function. This is easier than specifying with the complex or the real part separately. We can then print out the complex number with the print function Classes 2

3 Structures and Member Functions Place prototype of function inside the struct declaration Functions are normal, not inline Use scope to specify which structure function belongs to (i.e. _mycomplex::...) struct _mycomplex double re, im; void print(void); void setri(double a, double b); ; void _mycomplex::print(void) cout << noshowpos << re << showpos << im << "j" << noshowpos; void _mycomplex::setri( double a, double b) re = a; im = b; 3 In order to avoid the potential code size problems with inline functions, we can declare our functions outside the structure declaration. This way the compiler will create only one instance of the function and the calling code will jump to it. To declare the functions outside the structure, we need to tell the compiler what structure the function refers to as it is possible to have the same function names in different structures. We do this using the scope operator (::). We first place the return type, but we attach the structure name followed by the scope operator (::) and then the function name. So, the print function from the previous slide would be declared as void _mycomplex::print(void), and this declaration would be outside the structure declaration Classes 3

4 Structures and Member Functions Adding more functions to the structure makes manipulating the data easier Example: create addri function to add numbers to _mycomplex structure print and setri previously declared struct _mycomplex void addri(double a, double b); ; void _mycomplex::addri( double a, double b) re += a; im += b; int main(void) struct _mycomplex c; c.setri(5,10); //c=5+10j c.print(); // print c c.addri(5,-20);//c=10-10j c.print(); // print c 4 We can create more useful functions depending on the contents and meaning of our structure. For example, adding complex variables requires two additions. Other complex operations such as multiplication and division require many more normal operations. So it would be useful to do the same for these. In this example, we create a new member function addri which adds a real and imaginary component to our current complex number. The main function shows c being set and then having 5-20j added to it. Again, we don t have to worry about the actual variables in the structure since our function handles all that for us Classes 4

5 Structures and Data Protection We can protect the data in our structure by limiting the access to any member (function or variable) Example: Won t compile because main cannot see imag2, it is private to the structure Only functions in the _mycomplex structure can call imag2 struct _mycomplex public: double re, im; private: double imag2(); ; double _mycomplex::imag2() return im*im; int main(void) struct _mycomplex c; double d; c.set(1,2); // c=1+2j d=c.imag2(); // error 5 The nice part about creating member functions is that we really don t need to know anything about the structure internal variables in order to use it. So it makes sense that since calling functions don t need to know this information, why make it available to them? There may be a particular application where your structure contains dependent information, such that changing a single element requires the change of another. A possible problem may be that the user of this structure may not know this and end up causing errors in the data. To avoid this problem, we can make information in the structure private to only the functions in the structure. This way, a user cannot change or use members in the structure unless it is allowed. In this example, the member function imag2 can only be called by functions within the structure (i.e. print, setri, addri). If we try to call the function outside of the structure, the compiler will give us an error. Although we know it is there the compiler will not allow it. We apply the private attribute to any function or variable. Once set any members after it will have that attribute (either public of private). By default, all members are public Classes 5

6 Classes Although we can use structures to do many things, at some point (soon) we will find ourselves limited C++ uses another data container similar to structures known as a Class A Class, just as a structures, is a template Declaring an instance of a built-in data type results in a variable Declaring an instance of a class results in an object (Hence the name object-oriented-programming, OPP) Classes can have constructors and destructors 6 Depending on the size of the programming project, structures may not be appropriate for data management. There are limitations to what structures can do for us. C++ introduces a new data container known as classes. Classes are similar to structures in that they are templates for data, but they have many more usable features. The term object applies to what a class instantiates. An instance of a data type (int, double, etc.) is a variable, but the instance of a class is an object. One of the most important features of classes is the ability to have constructors and destructors. A constructor is a member function that is called when ever an object is instantiated (at the beginning of a function or when using new ). A destructor is a member function that is called when ever an object is removed (i.e. when you leave a function or using delete ) Classes 6

7 Classes Using classes makes building larger projects/programs easier Projects can be divided into many classes, each of which has its own responsibilities More people can work on a single project (e.g. one person per class) We write less code by reusing code which we ve already written Achieved by planning out and testing the classes before programming the whole project Less chance for human errors Use organization and data protection features 7 Using classes makes programming large projects easier. A program s end result can be analyzed and divided up into a series of classes, each responsible for a particular part of the process. By their nature, we can easily delegate each programmers task to a particular class. By analyzing how the classes would interact, we can reduce coding and hopefully reuse code between classes. Using classes will reduce the chance for human error in software. Human error is the main reason programs fail Classes 7

8 Objects and this pointer When running code in an object, the computer keeps track of the variables in the object with a pointer We can access this pointer as the variable this this is always defined in the context of our object Example: this inside a->function( ) is equal to a this inside b.add( ) is a pointer to b All variables used in the function methods essentially have a this-> in front of them 8 The compiler keeps track of objects by using pointers. Although a class may have functions associated with it, those functions (unless inline ) appear once in the whole program. These functions modify/use the appropriate object because it uses a pointer to address the data (variables in the object). Sometime it can be very useful to have access to this pointer. We can do this, and this pointer is known as the this pointer in the member function. For example, a.function( ) is a function within object a. To address the pointer of a in the function, we simply refer to it as this Classes 8

9 Example: Complex Number Class What do we need? Keep data private Real and Imaginary parts of the number A way to set the real and imaginary parts, from doubles or another complex number Addition, subtraction, multiplication, division and magnitude functions Get either the real or imaginary number Print out the number (both real and imaginary) Set the number to zero initially (constructor) 9 We will now develop a class for a complex number. The slide details the features of the class. We will use this information to develop the template of our class (next slide) Classes 9

10 Example: Complex Class (p.1) class Complex private: double re, im; public: Complex(double real=0, double imag=0); //Constructor ~Complex(); //Destructor void setri(double real=0, double imag=0); double getreal(); double getimag(); void setreal(double real=0); void setimag(double imag=0); void add(double real, double imag); void add(complex &c); void add(complex &c1, Complex &c2); // Other math functions here void print(); ; 10 Do define a class, we use a similar syntax as to that of a structure. We first place class followed by the name of the class. Here we use Complex. Depending on your compiler, complex may already be defined as a complex class (it is typical to find complex number classes pre-defined in compilers). You may need to rename it if this doesn t work on your compiler. Next we add the braces to define the contents of the class. One of our specifications was to keep the data private from other functions. To do this, we declare the real (re) and imaginary (im) parts as doubles, but with a private attribute. No other functions, other than those in the Complex class can read this information. We move on to the methods (functions) of the class. All of the methods will be public, so any function can call upon them. The first method defined is Complex this is the constructor because it has the same name as the class. It does not return anything, so do not place anything before it. In this case, the constructor takes 2 arguments, real and imag. If they are not provided, they will be set to zero before the function is called. The next method defined is ~Complex this is the destructor because it has the same name as the class and has a tilde (~) in front of it. Destructors return nothing, and they take no arguments. The next four functions facility a way we can access the contents of the complex numbers without directly accessing the variables. For the set functions, the arguments default to 0. Next we have three variations on the add function. The first one adds separate numbers to the real, and complex component of the current object. The second adds a complex number to the current complex object. And the third adds two complex objects together to generate the sum. Lastly, we declare our print routine which is a copy of that from the complex structure shown in previous slides Classes 10

11 Example: Complex Class (p.2) void Complex::setri(double real, double imag) re = real; im = imag; double Complex::getReal() return re; // same as this->re double Complex::getImag() return im; void Complex::setReal(double real) re = real; void Complex::setImag(double imag) im = imag; Complex::Complex(double real, double imag) setri(real, imag); ; 11 Once the class is defined (variables and methods), we can write the code of the methods. Since we are writing these functions outside the class declaration, they will not be considered to be inline, however, it would probably be more efficient if some of them were. First we declare setri as it is used to set the values of both the real and imaginary part of the complex number. It simply takes the variables passed (real, imag) and sets them to those of the class. We also declare the four functions we will use to allow external functions access to the data of the class: getreal, getimag, setreal, setimag. These functions are straight forward. We end this slide by defining the constructor. The constructor uses the variables passed (real, imag) and calls the setri function to apply them to the class variables. Although we could have simply wrote the code here, this helps because we are reusing some of our code already Classes 11

12 Example: Complex Class (p.3) Complex::~Complex() ; void Complex::add(double real, double imag) re += real; im += imag; void Complex::add(Complex &c) re += c.re; im += c.im; void Complex::add(Complex &c1, Complex &c2) re = c1.re + c2.re; im = c1.im + c2.im; void Complex::print() cout << noshowpos << re << showpos << im << "j" << noshowpos; 12 We continue with the definition of the class functions. First, on this slide, is the destructor. Again, no return type and no arguments. Since we haven t allocated memory in our constructor, we don t need a destructor. We add it here for informational purposes. When we develop a class for a matrix, we will be coding for a destructor. The next three functions are variations on the types of additions offered in this class. The first adds a separate set of real and doubles to the current object. The second adds a complex number to the current object, and the third uses the sum of two other complex objects to set the current object. Lastly we have our print function, we use the same from our previous complex structure Classes 12

13 Example: Complex Class (p.4) int main(void) Complex a; // "a" is set to 0+0j - constructor Complex b(1,2); // "b" is set to 1+2j - constructor Complex c(b); // "c" is set equal to "b" Complex *d; // "d" is just a pointer d = new Complex; // "d" is a pointer to 0+0j // "new" allocated memory and called the constructor a.add(10,20); // "a" = 0+0j j = 10+20j b.add(a); // "b" = 1+2j j = 11+22j d->add(b,c); // "*d" = 11+22j + 1+2j = 12+24j a.print(); b.print(); d->print(); delete d; // "destruct" d and un-allocate memory // Leaving function automatically destroys local // objects: a, b, and c. 13 Once our class and methods have been defined, we can use the class. We start our main function by declaring a Complex object a. As soon as this is executed, the object a is created and the constructor is called to build the object. Since we offered no arguments with a, the constructor will simply produce a complex number set to 0+0j. The next line, a complex number b is defined which is created and set to 1+2j. This is done by the constructor. The compiler sees that we ve provided b with arguments and it looks for the best constructor to use, in our case we only have one, but we could have many. The complex number c is also created. This is a copy of b. We didn t have to create this constructor (with the complex number as an argument) since the compiler did it for us. c is equal to b, but they are not the same, they occupy different memory. The compiler did the work to copy the contents of b to c. Lastly, *d is declared, but it is a pointer. No constructor is called because it is only a pointer. However, when we use the new command with d, the constructor is called after the memory for d is allocated. After the new statement, d is set to 0+0j. We can use our add functions now, the first, a.add(10,20) will add 10+20j to a, resulting in 10+20j since a was zero. Next, we add a to b. Since they are both complex numbers, the appropriate function will be called to do this work, resulting in 11+22j. Since d is a pointer, we must use -> to address the methods of d. We use a different add function to set d to the sum of both complex numbers b and c. We can use the print method to print the contents of a, b and d, but there will be no spaces between the numbers since we didn t print any of them. Once we are finished, we should un-allocate the memory we allocated for d. Before the d is un-allocated, the destructor is called and then the memory is un-allocated. We then leave the function, but since a, b and c are object they will all be destroyed by having their destructor called Classes 13

14 Example: Complex Class w/overload When we use the statement, for example: a = b + c; The compiler internally calls a function similar to: a = b.add(c); Depending on the expression, the compiler creates a temporary variable ( t for example), stores the sum of b and c, then copies that to a t = b + c; a = t; ( t is then removed) t only exists for the time of the expression 14 Although we created several adding functions for our complex class, it would be best to have the compiler handle the appropriate function calling for us. We can use operator overloading to have the compiler call only one function for addition. It will do the work for us. When ever we perform an addition or any other math operation, the computer is really looking at that math operation as a function of the first operand (or argument). In the example of a=b+c, b is the first operand/argument. So the computer sees the addition as a function of b. We can rewrite this as a=b.add(c) where add is a function of object b. c becomes an argument for the function add of b. When we use the addition operator on an object, this is what will essentially happen. We need to create the add function for the object (next slide). Sometimes, depending on the expression we create, the compiler will have to create temporary variables/objects. This may happen quite often when dealing with objects. In the case of a=b+c, the compiler may create a new variable/object, for example, t which will hold the sum of b and c. Once that is done, the temporary variable will be copied to a, and then the temporary variable/object is removed Classes 14

15 Example: Complex Class w/overload class Complex public: Complex operator+(const Complex &rhs); ; Complex Complex::operator+(const Complex &rhs) Complex t; t.re = re + rhs.re; t.im = im + rhs.im; return t; 15 In order to take advantage of the C++ operator overload feature, we must include a prototype or function in our class definition. Assuming our previous class definition, we include a new function operator+. This is a special name as the compiler will know how to make reference to it. Our function returns a complex variable, as it should. It requires one argument, and that is const Complex &rhs, or the Right Hand Side of the equation whereas the current object is the Left Hand Side. We know that it accepts a complex number, and the & implies that the compiler will handle the pointer references for us. What we haven t see is the term const. We use this to tell the compiler that what we are passing to this function will be constant and we won t be able to change it in the function. Although it may sound bizarre, we could change the contents of the objects passed to us we ve done this before (sumavg example). Since we are allowing the compiler to handle the pointers, we could unintentionally change the passed information. To prevent us from doing this, we place the const term in front of the passed variable rhs. const will also prevent us from calling any methods associated with the parameter since they could change it s value in someway. Remember, in C++ we can have several functions with the same name, but different parameters. This one declaration will force the compiler to change any type of function call to our addition function so that it meets the requirements. After we ve declared our function prototype, we can actually write it. We do this by stating the function return value, the class, scope ::, function name and then arguments just like those in the prototype. Our function is simple, we create a new complex number t and add the contents of the current object to the contents of the object passed ( c ). When we are done, we return our new object t in this case Classes 15

16 Example: Complex Class w/overload int main(void) Complex a; // "a" is set to 0+0j - constructor Complex b(1,2); // "b" is set to 1+2j - constructor Complex c(3,4); // "c" is set to 3+4j - constructor Complex d(5,6); // "d" is set to 5+6j - constructor a = b + c + d; // "a" = 1+2j + 3+4j + 5+6j = 9+12j b = Complex(10,20) + a; // "b" = 10+20j j = 19+32j a.print(); b.print(); // Leaving function automatically destroys local // objects: a, b, c, and d. 16 We can now use the addition operator easily now just as if we were working with normal numbers. In this example, we declare a few complex objects and initialize them. We then use these numbers with the addition operator + with a = b+c+d. The compiler will now do all the work to call the addition function to provide the proper result. For this line, the solution is 9+12j. In C++ we can declare variables anywhere, we don t even need to give them names if we only use them once. In the next statement b = Complex(10,20)+a, we create a complex number 10+20j and add it to a. Once the operation is done, this number 10+20j no longer exists. It served its purpose and it has been removed. Operator overloading certainly makes our life easier when it comes to using our own classes with arithmetic Classes 16

17 Example: Complex Class w/overload (Adding to cout ) ostream& operator<<(ostream &os, Complex &a) os << noshowpos << a.getreal() << showpos; os << a.getimag() << "j" << noshowpos; return os; int main(void) Complex a; // "a" is set to 0+0j - constructor Complex b(1,2); // "b" is set to 1+2j - constructor Complex c(3,4); // "c" is set to 3+4j - constructor Complex d(5,6); // "d" is set to 5+6j - constructor a = b + c + d; // "a" = 1+2j + 3+4j + 5+6j = 9+12j b = Complex(10,20) + a; // "b" = 10+20j j = 19+32j cout << a << " " << b << " " << c << " " << d << endl; // Leaving function automatically destroys local // objects: a, b, c, and d. 17 We could eliminate the need for our print() function by adding some code to tell cout how to print a complex object. cout is an object based on the class ostream. This adds an additional operator overload for << to this class to handle our complex class. os takes place of cout here. We simply call them members of our complex class to get the data we need to print. Remember in this case that this code is for ostream and not Complex so we can only call the members that are public. We also have to return os to ensure we can chain more than one of the << operations together. YOU WILL NOT BE TESTED ON THIS SLIDE Classes 17

18 Example: Matrix Class What do we need? Keep data private Addition, subtraction, multiplication functions Data for matrix Print out the matrix A way to address all elements of the matrix Get rows/cols Allocate and Unallocate the memory (constructors and destructors) 18 Now that we ve created a complex number class, we will try to do the same with a matrix class. This will be slightly more difficult as we will be using some dynamic memory (in the constructors and destructors). We ideally would like to keep the matrix data private, but we will allow it to be public for now. We will be adding functions to get the rows and columns, perform addition and other arithmetic Classes 18

19 Example: Matrix Class (p.1) class Matrix public: // would like this to be private eventually double **m; int NR, NC; public: Matrix(); //Constructor Matrix(int rows, int cols); //Constructor Matrix(const Matrix &a); // Constructor ~Matrix(); //Destructor void allocate(int rows, int cols); void unallocate(); int getrows(); int getcols(); void zero(); Matrix operator+(const Matrix &rhs); Matrix &operator=(const Matrix &rhs); // Add other math functions later void print(); ; 19 This is our class definition for Matrix. We start our with our members: m, NR, and NC. m is the pointer to where are matrix is stored (this is the same as before when we dealt with matrices). NR is the number of rows, and NC is the number of columns. These members are public, for now. We then declare all our method functions. We first declare three constructors, one of which takes nothing, the next takes the rows and columns of the matrix, and the last is meant to create a new matrix from an existing one. Since our matrices can be any size, it is best not to assume there is a default size. What we will do instead is create the matrix only if the dimensions are given. Otherwise, we ll wait until some type of operation is imposed on us to create the matrix. We also include a destructor so that we can clean up the dynamic memory that we will allocate. Since it is possible that we will be allocating/un-allocating the matrix during some arithmetic functions, we will create functions to do this for us. allocate sets up a matrix while unallocate removes it. Our constructor and destructors will call these functions. It is not good practice to call constructors and destructors directly within your class. We supply a couple of other functions such as getrows and getcols so that we can find out how large our matrix is. We also include operator overloading for addition and setting a matrix equal to another. We need to create an overloaded operator for = because we are using dynamic memory. If, for example, we had two matrices A and B, and wanted to set B=A, the compiler would simply copy the member contents from B to A. Unfortunately one of these contents is m, a pointer. So if we set B=A and then changes some element in matrix B, we would also be changing A because they point to the same data. This would be very bad. So we must create a function that will copy the contents of one matrix to another matrix. We also include a print function so we can see our matrices Classes 19

20 Example: Matrix Class (p.2) void Matrix::allocate(int rows, int cols) if( rows>0 && cols>0 ) NR = rows; NC = cols; m = new double * [NR]; for(int i=0;i<nr;i++) m[i] = new double [NC]; else NR = 0; NC = 0; m = 0; void Matrix::unallocate() if (m) for(int i=0;i<nr;i++) delete [] m[i]; delete [] m; NR = 0; NC = 0; m = 0; 20 Our allocate function is basically a copy of what we did previously, but with some extra code for error checking. It is possible someone may ask for a matrix of zero rows. What does that mean? Well, it is a problem. We won t allow this, so if this does happen, we will not create the matrix. We set the number of rows, columns and the data pointer to zero. When the data pointer is zero, it tells use that there is no data and the matrix is not set. For removing the matrix, we have to make sure it actually exists, so we check the data pointer m to see if it is not zero. Only if it points to something do we un-allocate the memory. You may also notice we are using delete [] on our arrays. We didn t do this before because we were only dealing with native datatypes like int, float, double, etc. Now since it is possible we could be using other object we have to use delete [] when deleting any arrays of objects we created. We will see this later Classes 20

21 Example: Matrix Class (p.3) Matrix::Matrix() NR = 0; NC = 0; m = 0; Matrix::Matrix(int rows, int cols) allocate(rows, cols); Matrix::Matrix(const Matrix &a) allocate(a.nr, a.nc); for (int i = 0; i<nr; i++) for (int j = 0; j<nc; j++) m[i][j] = a.m[i][j]; Matrix::~Matrix() unallocate(); 21 Our basic constructor is quite simple set all member variables to zero. We only use this constructor if the matrix is to be defined, but not set. In the next function, we are given parameters to set the matrix size. For this, we just call the allocate function as it does all that is necessary (set the variables and allocate the memory). Because we are using dynamic memory in our matrix we need to make special consideration for copies made from it. So if we were to create a new matrix based on another they would be two different matrices. So we need to add a special constructor which will copy one matrix to another. This wasn t necessary with our Complex class since there was no dynamic memory and all information was in the member data. The code first allocates the matrix size to the one we are copying from and then it copies each element one by one. Our destructor does the opposite of the constructors, it un-allocates the dynamic memory by calling unallocate. The memory for the object (m, NR, NC) is unallocated by the compiler so we don t have to worry about that Classes 21

22 Example: Matrix Class (p.4) Matrix Matrix::operator+(const Matrix &rhs) Matrix t; if(nr!=rhs.nr NC!=rhs.NC) cout << "Matrices not the same size." << endl; else t.allocate(nr, NC); for(int i=0;i<nr;i++) for(int j=0;j<nc;j++) t.m[i][j]=m[i][j]+rhs.m[i][j]; return t; 22 Our add function is very similar in declaration to that of our Complex add function. We simply replace the term Complex with Matrix. Our function will return a Matrix and accept a constant Matrix a. Before performing any addition, we must make sure the matrices match in size. So we compare the current matrix with the one passed ( a ). If they don t match we simply write a message, but still return the new matrix. Although this isn t the best way to resolve this situation, it is the best we can do right now. C++ has other features to better adapt for this type of error, but we won t cover them here. Once we ve verified the matrices are the same, we create t to the correct dimensions with the allocate function. We then go though each row and column adding the appropriate elements together and storing them into t. We end by returning the sum matrix t Classes 22

23 Example: Matrix Class (p.5) Matrix &Matrix::operator=(const Matrix &rhs) if (this!= &rhs) if(nr!=rhs.nr NC!=rhs.NC) unallocate(); allocate(rhs.nr, rhs.nc); for(int i=0;i<nr;i++) for(int j=0;j<nc;j++) m[i][j]=rhs.m[i][j]; return *this; 23 As mentioned before, we need to create a = operator for this matrix class since we use dynamic memory. Our function declaration is a little different from the + operator. The overloading of = requires us to return a pointer to our current object. This may sound confusing, but this is they way the C++ people set this up. So our function will work such that we are setting the current object equal to the one that is passed to us. The first thing we need to check is to see if we are setting the same matrices equal this can happen with the C++ compiler. So we check to see if the object pointer passed is equal to this, if so, do nothing but end appropriately. The second thing we check is to see if the matrices are the same size this is possible. This will improve the speed of the operator so we don t recreate a matrix if it is already the proper size. If the sizes are not the same, we unallocate the old data and reallocate new data to the appropriate size. We then create a loop to copy all the contents from the passed matrix to the other. When we are done, we have to pass back our current object. Since we used a reference in our return object, we have to pass the object and the only way to get this is to use *this Classes 23

24 Example: Matrix Class (p.6) void Matrix::zero() if (!m) cout << "Matrix not sized yet." << endl; else for(int i=0;i<nr;i++) for(int j=0;j<nc;j++) m[i][j] = 0; int Matrix::getRows() return NR; int Matrix::getCols() return NC; void Matrix::print() for (int i = 0; i<nr; i++) for (int j = 0; j<nc; j++) cout << m[i][j] << " "; cout << endl; 24 Here are the definitions of some utility functions of this class. zero() sets the elements of the matrix to zero. However, it checks first to see if the data exists. getrows() and getcols() returns the appropriate values of the matrix dimensions. We also define our matrix print function. It simply prints out each element of a row, followed by a new line Classes 24

25 Example: Matrix Class (p.7) int main(void) Matrix A(2,2); A.zero(); Matrix B(2,2); B.zero(); A.m[0][0]=1; A.m[0][1]=2; A.m[1][0]=3; A.m[1][1]=4; B.m[0][0]=5; B.m[0][1]=6; B.m[1][0]=7; B.m[1][1]=8; cout << "Matrix A:" << endl; A.print(); cout << "Matrix B:" << endl; B.print(); Matrix C; C = A + B; cout << "Matrix C:" << endl; C.print(); 25 Here is the example main function. Here we setup two matrices, A and B and initialized them with some numbers. We can then output their contents using the print() function and then we will add A and B together to produce C. We can do this with the + operator we overloaded it so it does what we want. Although we don t see it happening, the = operator is also being used here to set C equal to the temporary variable created when adding A and B. Later, we print out the contents of matrix C Classes 25

26 Example: Matrix Class - Output Matrix A: Matrix B: Matrix C: This is the output you would expect from the above program Classes 26

27 Extending the Matrix Class Make all the data of the matrix private Add functions to read and write to a specified row and column Slower, but matrix is completely managed by the class Add matrix inversion Gauss-Jordan with maximum pivot Apply diagonal to equation constants Only NxN matrix 27 Our Matrix class should be truly private to avoid any potential data corruption. To stop others from accessing the matrix elements m, we will employ the use of two method functions, one to set the elements and one to get the elements. This may slow down the interfacing code between the class and other functions, but it is worth having. We will also add matrix inversion to our class. We can perform inversion using the Gauss- Jordan method with maximum pivot. To do this, we apply a diagonal matrix to our existing one, perform the solution and then remove the diagonal matrix. Inversion can only apply to NxN matrices Classes 27

28 Example: Extended Matrix Class (p.1) class Matrix private: // all data is private double **m; int NR, NC; public: // Assume previously declared functions were here // Should add array bounds checking in these functions void set(double val, int rows, int cols) m[rows][cols] = val; double get(int rows, int cols) return m[rows][cols]; int gaussjordan(); int invert(); void addcolumns(int cols); // Add columns for I-mat void removecolumns(int cols); // Remove columns of I-mat ; 28 This is our class description again, but only with additions. Assume that all the other functions previously are declared. The first thing we do is change the member variables to private. This will ensure that no other code will be able to change the contents of our variables. But in doing this, we need to facility a way to allow other functions outside of this class to setup the matrix. We declare two functions, set and get which will let us set and retrieve elements of the matrix. The functions are fully declared in the class so they will be inline functions. Effectively the will only be one line in the other functions code. This really won t cause any performance degradation. We then declare our gaussjordan function. This is similar to the function we created in previous lectures, but we don t need to pass the matrix information to the function. It is able to get that from the class. We also declare an invert function, again with no arguments all that information is in the class. In order to make inversion easier, we will create two utility functions that will add columns to the end of the matrix, and remove columns from the beginning. We do this so we can add and remove the identity matrix Classes 28

29 Example: Extended Matrix Class (p.2) int Matrix::gaussjordan() int i, j, k; double *t; int BIGrow; for(j=0;j<nr;j++) // Find Maximum Pivot BIGrow=j; for(i=j+1;i<nr;i++) if(fabs(m[i][j])>fabs(m[bigrow][j])) BIGrow=i; if(fabs(m[bigrow][j])<1e-7) return 1; 29 This slide shows half of the gauss-jordan with maximum pivot code. It is essentially a copy from earlier lectures with a few variable changes. The code loops through each row, first looking for the maximum pivot and then swapping rows if needed. That row is then normalized and the pivot column is then eliminated from all the other rows Classes 29

30 Example: Extended Matrix Class (p.3) t=m[j]; m[j]=m[bigrow]; m[bigrow]=t; // Normalization for(i=j+1;i<nc;i++) m[j][i]/=m[j][j]; m[j][j]=1.0; // Elimination for(k=0;k<nr;k++) if(k==j) continue; // Restart Loop for(i=j+1;i<nc;i++) m[k][i]-=m[j][i]*m[k][j]; m[k][j]=0.0; return 0; Classes 30

31 Example: Extended Matrix Class (p.4) void Matrix::addcolumns(int cols) double *t; int i, j; if (!m) cout << "Matrix is not set." << endl; return; for(i=0;i<nr;i++) t = new double [NC+cols]; for(j=0;j<nc;j++) t[j]=m[i][j]; for(;j<nc+cols;j++) t[j]=0; delete [] m[i]; m[i] = t; NC+=cols; 31 This is our add column function. It will add cols columns to the right of the matrix and set the new elements to zero. However, we will first check to see if the matrix is defined. If not, leave this function. Our approach here is for each row in the matrix, create a new row (with cols more elements), copy the elements from the old row to the new row, and set the new elements to zero. For example, if our matrix is 2x2 and we ask to add two columns: A B is going to be A B 0 0 after the function is done C D C D 0 0 We first loop through all the rows ( j is our index). We then allocate a new array of numbers (current number of columns plus the passed value). Then, each element from the current row is copied to the new one. After, the remaining elements are set to zero. The new row is complete. We must then remove the current or old row by using the delete function to un allocate the memory. Once that is done, we assign the new row to the row pointer so we know where it is and how to get to it. We finish the function by updating the number of columns in the matrix Classes 31

32 Example: Extended Matrix Class (p.5) void Matrix::removecolumns(int cols) double *t; int i, j; if (!m) cout << "Matrix is not set." << endl; return; NC-=cols; for(i=0;i<nr;i++) t = new double [NC]; for(j=0;j<nc;j++) t[j]=m[i][j+cols]; delete [] m[i]; m[i] = t; 32 The removecolumns function is essentially the opposite of the addcolumns function. First, we check to see if the matrix size is set. If not, we leave the function. We then update the number of columns in the matrix. We could do this later, but we save on temporary variables by doing it now. We then go through each row, again allocating memory for a new row (the number of columns being smaller now). We then copy the elements from the right of the old row to the left of the new row. Once that is done, we un allocate the old row and set the row pointer to the new row. For example, if our matrix is 4x2 and we ask to remove two columns: 0 0 A B is going to be A B after the function is done 0 0 C D C D Classes 32

33 Example: Extended Matrix Class (p.6) int Matrix::invert() int i, j; if (!m) cout << "Matrix is not set." << endl; return 1; if (NC!=NR) cout << "Matrix must be square." << endl; return 1; addcolumns(j=nc); for(i=0;i<nr;i++) m[i][j+i] = 1; i=gaussjordan(); removecolumns(j); return i; 33 Now that we have these two utility functions, we can use them to help perform the inversion. Our function must first check to see if the matrix is set, if not, leave. We then check to see if the matrix is a NxN, that is if the rows and the columns are the same. If not, leave. Now that we ve established that the matrix exists and it is square, we can the add the columns. We add the same number of columns as there are rows/columns. We save the number of columns before we call the function so that we know how many to remove later. Next we set the new columns to the identity matrix, for example: A B 0 0 will be set to A B 1 0 C D 0 0 C D 0 1 We then call the gauss-jordan method to solve the matrix and when it is done we have a form like: 1 0 E F 0 1 G H We then call the removecolumns function to remove the identity matrix part. Once that is done, we return the error value from the gaussjordan solution, if there was any Classes 33

34 Example: Extended Matrix Class (p.7) int main(void) Matrix A(2,2); A.zero(); Matrix B(2,2); B.zero(); A.set(1,0,0); A.set(2,0,1); A.set(3,1,0); A.set(4,1,1); B.set(5,0,0); B.set(6,0,1); B.set(7,1,0); B.set(8,1,1); cout << "Matrix A:" << endl; A.print(); cout << "Matrix B:" << endl; B.print(); Matrix C; C = A + B; cout << "Matrix C:" << endl; C.print(); C.invert(); cout << "Inversion of Matrix C:" << endl; C.print(); C.invert(); cout << "Inversion of Matrix C:" << endl; C.print(); 34 In our main function we have to change the way we set the elements of the matrix. We can t directly address is anymore, so we have to use the set function. We do this to set the contents of A and B. We then print out A and B, sum them up into C and print matrix C out. We can then call the invert function to invert C. Doing this will erase the old contents of C. We then print out C, which is the inversion of A+B. We can get back the old contents of C by inverting it again Classes 34

35 Example: Extended Matrix Class - Output Matrix A: Matrix B: Matrix C: Inversion of Matrix C: Inversion of Matrix C: This is the expected output of the program Classes 35

36 Example: Extended Matrix Class (Adding to cout ) ostream& operator<<(ostream &os, Matrix &a) for(int i=0;i<a.getrows();i++) for(int j=0;j<a.getcols();j++) os << a.get(i,j) << " "; os << endl; return os; 36 We could eliminate the need for our print() function by adding some code to tell cout how to print a matrix. cout is an object based on the class ostream. This adds an additional operator overload for << to this class to handle our matrix class. os takes place of cout here. We simply call them members of our Matrix class to get the data we need to print. Remember in this case that this code is for ostream and not Matrix so we can only call the members that are public. We also have to return os to ensure we can chain more than one of the << operations together. YOU WILL NOT BE TESTED ON THIS SLIDE Classes 36

37 Example: Extended Matrix Class (p.7 w/ new cout function) int main(void) Matrix A(2,2); A.zero(); Matrix B(2,2); B.zero(); A.set(1,0,0); A.set(2,0,1); A.set(3,1,0); A.set(4,1,1); B.set(5,0,0); B.set(6,0,1); B.set(7,1,0); B.set(8,1,1); cout << "Matrix A:" << endl << A; cout << "Matrix B:" << endl << B; Matrix C; C = A + B; cout << "Matrix C:" << endl << C; C.invert(); cout << "Inversion of Matrix C:" << endl << C; C.invert(); cout << "Inversion of Matrix C:" << endl << C; 37 This is a variation of the main code presented earlier with the addition of using the Matrix objects directly with cout. YOU WILL NOT BE TESTED ON THIS SLIDE Classes 37

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory Pointers A pointer is simply a reference to a variable/object Compilers automatically generate code to store/retrieve variables from memory It is automatically generating internal pointers We don t have

More information

Chapter V. Building Classes

Chapter V. Building Classes 78 Chapter V Building Classes A class embodies a set of variables and a set of functions that may operate on the variables in the class. These variables and functions are referred to as members of that

More information

CS11 Intro C++ Spring 2018 Lecture 5

CS11 Intro C++ Spring 2018 Lecture 5 CS11 Intro C++ Spring 2018 Lecture 5 C++ Abstractions C++ provides rich capabilities for creating abstractions class Complex { double re, im; public: Complex(double re, double im);... ; Would be nice if

More information

ADTs in C++ In C++, member functions can be defined as part of a struct

ADTs in C++ In C++, member functions can be defined as part of a struct In C++, member functions can be defined as part of a struct ADTs in C++ struct Complex { ; void Complex::init(double r, double i) { im = i; int main () { Complex c1, c2; c1.init(3.0, 2.0); c2.init(4.0,

More information

And Even More and More C++ Fundamentals of Computer Science

And Even More and More C++ Fundamentals of Computer Science And Even More and More C++ Fundamentals of Computer Science Outline C++ Classes Special Members Friendship Classes are an expanded version of data structures (structs) Like structs, the hold data members

More information

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms AUTO POINTER (AUTO_PTR) //Example showing a bad situation with naked pointers void MyFunction()

More information

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak! //Example showing a bad situation with naked pointers CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms void MyFunction() MyClass* ptr( new

More information

Roxana Dumitrescu. C++ in Financial Mathematics

Roxana Dumitrescu. C++ in Financial Mathematics Roxana Dumitrescu C++ in Financial Mathematics What have we learnt? Arrays; relation between arrays and pointers.. Returning arrays from functions Passing arrays to functions Intoduction to classes Plan

More information

PIC 10A Objects/Classes

PIC 10A Objects/Classes PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous

More information

Laboration 1 Introduction: matrices

Laboration 1 Introduction: matrices Introduction Laboration 1 Introduction: matrices This is an introductionary laboration that does not have to be handed in. I still recommend that you do it, though, to get started using C++. If you are

More information

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer September 26, 2016 OOPP / C++ Lecture 4... 1/33 Global vs. Class Static Parameters Move Semantics OOPP / C++ Lecture 4... 2/33 Global Functions

More information

CS 7B - Spring Final Exam

CS 7B - Spring Final Exam CS 7B - Spring 2018 - Final Exam Write your responses to following questions on this paper, or attach extra, as needed. sentences where appropriate and write out code using proper style and syntax. 1.

More information

Ch. 12: Operator Overloading

Ch. 12: Operator Overloading Ch. 12: Operator Overloading Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42

More information

Programming, numerics and optimization

Programming, numerics and optimization Programming, numerics and optimization Lecture A-4: Object-oriented programming Łukasz Jankowski ljank@ippt.pan.pl Institute of Fundamental Technological Research Room 4.32, Phone +22.8261281 ext. 428

More information

Operator overloading

Operator overloading 1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

A brief introduction to C++

A brief introduction to C++ A brief introduction to C++ Rupert Nash r.nash@epcc.ed.ac.uk 13 June 2018 1 References Bjarne Stroustrup, Programming: Principles and Practice Using C++ (2nd Ed.). Assumes very little but it s long Bjarne

More information

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26 COSC 2P95 Procedural Abstraction Week 3 Brock University Brock University (Week 3) Procedural Abstraction 1 / 26 Procedural Abstraction We ve already discussed how to arrange complex sets of actions (e.g.

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

Functions, Pointers, and the Basics of C++ Classes

Functions, Pointers, and the Basics of C++ Classes Functions, Pointers, and the Basics of C++ Classes William E. Skeith III Functions in C++ Vocabulary You should be familiar with all of the following terms already, but if not, you will be after today.

More information

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 4 Date:

More information

Lecture 14: more class, C++ streams

Lecture 14: more class, C++ streams CIS 330: / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 14:

More information

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor Outline EDAF50 C++ Programming 4. Classes Sven Gestegård Robertz Computer Science, LTH 2018 1 Classes the pointer this const for objects and members Copying objects friend inline 4. Classes 2/1 User-dened

More information

POINTERS - Pointer is a variable that holds a memory address of another variable of same type. - It supports dynamic allocation routines. - It can improve the efficiency of certain routines. C++ Memory

More information

UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING

UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING CMPE13/L: INTRODUCTION TO PROGRAMMING IN C SPRING 2012 Lab 3 Matrix Math Introduction Reading In this lab you will write a

More information

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team Question No: 1 ( Marks: 2 ) Write a declaration statement for an array of 10

More information

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects Vectors of Objects As we have mentioned earlier, you should almost always use vectors instead of arrays. If you need to keep track of persons (objects of class Person), you must decide what to store in

More information

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity. OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

More information

B16 Object Oriented Programming

B16 Object Oriented Programming B16 Object Oriented Programming Michael A. Osborne mosb@robots.ox.ac.uk http://www.robots.ox.ac.uk/~mosb/teaching.html#b16 Hilary 2013 Topic 4: Constructors Recall our definition of the Complex class.

More information

Function Overloading

Function Overloading Function Overloading C++ supports writing more than one function with the same name but different argument lists How does the compiler know which one the programmer is calling? They have different signatures

More information

Introduction Of Classes ( OOPS )

Introduction Of Classes ( OOPS ) Introduction Of Classes ( OOPS ) Classes (I) A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class.

More information

Classes. Christian Schumacher, Info1 D-MAVT 2013

Classes. Christian Schumacher, Info1 D-MAVT 2013 Classes Christian Schumacher, chschuma@inf.ethz.ch Info1 D-MAVT 2013 Object-Oriented Programming Defining and using classes Constructors & destructors Operators friend, this, const Example Student management

More information

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University (5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University Key Concepts Function templates Defining classes with member functions The Rule

More information

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved. Chapter 10 Pointers and Dynamic Arrays Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives Pointers Pointer variables Memory management Dynamic Arrays Creating and using Pointer arithmetic

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010 CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 2 Date:

More information

Computer Science II CSci 1200 Lecture 18 Operators and Friends

Computer Science II CSci 1200 Lecture 18 Operators and Friends Review from Lecture 17 Arrays and pointers Computer Science II CSci 1200 Lecture 18 Operators and Friends Different types of memory Dynamic allocation of arrays Today s Lecture Operators and Friends Chapter

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++ CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many

More information

IS0020 Program Design and Software Tools Midterm, Fall, 2004

IS0020 Program Design and Software Tools Midterm, Fall, 2004 IS0020 Program Design and Software Tools Midterm, Fall, 2004 Name: Instruction There are two parts in this test. The first part contains 22 questions worth 40 points you need to get 20 right to get the

More information

CS32 - Week 1. Umut Oztok. June 24, Umut Oztok CS32 - Week 1

CS32 - Week 1. Umut Oztok. June 24, Umut Oztok CS32 - Week 1 CS32 - Week 1 Umut Oztok June 24, 2016 Administration Email:umut@ucla.edu Office hours: R 09:30am-12:30pm (BH 4663) Constructor Special member function to initialize an instance of a class. Called whenever

More information

Implementing Abstract Data Types (ADT) using Classes

Implementing Abstract Data Types (ADT) using Classes Implementing Abstract Data Types (ADT) using Classes Class Definition class classname { public: //public member functions private: //private data members and member functions }; // Note the semicolon!

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #43 Multidimensional Arrays In this video will look at multi-dimensional arrays. (Refer Slide Time: 00:03) In

More information

EL2310 Scientific Programming

EL2310 Scientific Programming (pronobis@kth.se) Overview Overview Wrap Up Introduction to Object Oriented Paradigm More on and Members Operator Overloading Last time Intro to C++ Differences between C and C++ Intro to OOP Today Object

More information

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer June 3, 2013 OOPP / C++ Lecture 9... 1/40 Const Qualifiers Operator Extensions Polymorphism Abstract Classes Linear Data Structure Demo Ordered

More information

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo Chapter 10 Pointers and Dynamic Arrays 1 Learning Objectives Pointers Pointer variables Memory management Dynamic Arrays Creating and using Pointer arithmetic Classes, Pointers, Dynamic Arrays The this

More information

Overloading Operators in C++

Overloading Operators in C++ Overloading Operators in C++ C++ allows the programmer to redefine the function of most built-in operators on a class-by-class basis the operator keyword is used to declare a function that specifies what

More information

Come and join us at WebLyceum

Come and join us at WebLyceum Come and join us at WebLyceum For Past Papers, Quiz, Assignments, GDBs, Video Lectures etc Go to http://www.weblyceum.com and click Register In Case of any Problem Contact Administrators Rana Muhammad

More information

G52CPP C++ Programming Lecture 20

G52CPP C++ Programming Lecture 20 G52CPP C++ Programming Lecture 20 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Wrapping up Slicing Problem Smart pointers More C++ things Exams 2 The slicing problem 3 Objects are not

More information

CS11 Introduction to C++ Fall Lecture 3

CS11 Introduction to C++ Fall Lecture 3 CS11 Introduction to C++ Fall 2012-2013 Lecture 3 Topics for Today n C++ compilation process n Using the const keyword n Redefining operators for your classes C++ Compilation n You type: g++ -Wall point.cc

More information

Interview Questions of C++

Interview Questions of C++ Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.

More information

Ch. 11: References & the Copy-Constructor. - continued -

Ch. 11: References & the Copy-Constructor. - continued - Ch. 11: References & the Copy-Constructor - continued - const references When a reference is made const, it means that the object it refers cannot be changed through that reference - it may be changed

More information

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370 Part VII Object-Oriented Programming Philip Blakely (LSC) C++ Introduction 194 / 370 OOP Outline 24 Object-Oriented Programming 25 Member functions 26 Constructors 27 Destructors 28 More constructors Philip

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

C++ for Java Programmers

C++ for Java Programmers Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

B16 Object Oriented Programming

B16 Object Oriented Programming B16 Object Oriented Programming Michael A Osborne mosb@robots.ox.ac.uk http://www.robots.ox.ac.uk/~mosb/b16.html Hilary 2014 Topic 4: Constructors Recall our definition of the Complex class. class Complex

More information

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file? QUIZ on Ch.5 Why is it sometimes not a good idea to place the private part of the interface in a header file? Example projects where we don t want the implementation visible to the client programmer: The

More information

Review: C++ Basic Concepts. Dr. Yingwu Zhu

Review: C++ Basic Concepts. Dr. Yingwu Zhu Review: C++ Basic Concepts Dr. Yingwu Zhu Outline C++ class declaration Constructor Overloading functions Overloading operators Destructor Redundant declaration A Real-World Example Question #1: How to

More information

Pointers and References

Pointers and References Steven Zeil October 2, 2013 Contents 1 References 2 2 Pointers 8 21 Working with Pointers 8 211 Memory and C++ Programs 11 212 Allocating Data 15 22 Pointers Can Be Dangerous 17 3 The Secret World of Pointers

More information

CSE 303: Concepts and Tools for Software Development

CSE 303: Concepts and Tools for Software Development CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects

More information

AIMS Embedded Systems Programming MT 2017

AIMS Embedded Systems Programming MT 2017 AIMS Embedded Systems Programming MT 2017 Object-Oriented Programming with C++ Daniel Kroening University of Oxford, Computer Science Department Version 1.0, 2014 Outline Classes and Objects Constructors

More information

nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n

nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n Static and Dynamic Memory Allocation In this chapter we review the concepts of array and pointer and the use of the bracket operator for both arrays and pointers. We also review (or introduce) pointer

More information

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year Object Oriented Programming Assistant Lecture Omar Al Khayat 2 nd Year Syllabus Overview of C++ Program Principles of object oriented programming including classes Introduction to Object-Oriented Paradigm:Structures

More information

Outline. Dynamic Memory Classes Dynamic Memory Errors In-class Work. 1 Chapter 10: C++ Dynamic Memory

Outline. Dynamic Memory Classes Dynamic Memory Errors In-class Work. 1 Chapter 10: C++ Dynamic Memory Outline 1 Chapter 10: C++ Dynamic Memory Proper Memory Management Classes which must allocate memory must manage it properly. Default behavior of operations in C++ are insufficient for this. The assignment

More information

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management Session 8 Memory Management The issues Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Programs manipulate data, which must be stored

More information

Lesson 13 - Vectors Dynamic Data Storage

Lesson 13 - Vectors Dynamic Data Storage Lesson 13 - Vectors Dynamic Data Storage Summary In this lesson we introduce the Standard Template Library by demonstrating the use of Vectors to provide dynamic storage of data elements. New Concepts

More information

7.1 Optional Parameters

7.1 Optional Parameters Chapter 7: C++ Bells and Whistles A number of C++ features are introduced in this chapter: default parameters, const class members, and operator extensions. 7.1 Optional Parameters Purpose and Rules. Default

More information

Evolution of Programming Languages

Evolution of Programming Languages Evolution of Programming Languages 40's machine level raw binary 50's assembly language names for instructions and addresses very specific to each machine 60's high-level languages: Fortran, Cobol, Algol,

More information

ADTs & Classes. An introduction

ADTs & Classes. An introduction ADTs & Classes An introduction Quick review of OOP Object: combination of: data structures (describe object attributes) functions (describe object behaviors) Class: C++ mechanism used to represent an object

More information

What does it mean by information hiding? What are the advantages of it? {5 Marks}

What does it mean by information hiding? What are the advantages of it? {5 Marks} SECTION ONE (COMPULSORY) Question #1 [30 Marks] a) Describe the main characteristics of object-oriented programming. {5 Marks Encapsulation the ability to define a new type and a set of operations on that

More information

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science Written examination Homologation C++ and Computer Organization (2DMW00) Part I: C++ - on Tuesday, November 1st 2016, 9:00h-12:00h.

More information

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15 C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15 This chapter introduces the notion of dynamic memory allocation of variables and objects in a C++ program.

More information

During the course of writing the Matrix class we will cover some interesting C++ topics. Specically: constructors and destructors, operator

During the course of writing the Matrix class we will cover some interesting C++ topics. Specically: constructors and destructors, operator A Matrix Class During the course of writing the Matrix class we will cover some interesting C++ topics. Specically: constructors and destructors, operator overloading, the rule of three, returning references,

More information

Plan of the day. Today design of two types of container classes templates friend nested classes. BABAR C++ Course 103 Paul F. Kunz

Plan of the day. Today design of two types of container classes templates friend nested classes. BABAR C++ Course 103 Paul F. Kunz Plan of the day Where are we at? session 1: basic language constructs session 2: pointers and functions session 3: basic class and operator overloading Today design of two types of container classes templates

More information

Assignment of Objects

Assignment of Objects Copying Objects 1 Assignment of Objects 2 Slides 1. Table of Contents 2. Assignment of Objects 3. Dynamic Content 4. Shallow Copying 5. Deep Copying 6. this Pointer 7. Improved Deep Copy 8. Passing an

More information

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information

QUIZ Friends class Y;

QUIZ Friends class Y; QUIZ Friends class Y; Is a forward declaration neeed here? QUIZ Friends QUIZ Friends - CONCLUSION Forward (a.k.a. incomplete) declarations are needed only when we declare member functions as friends. They

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

G52CPP C++ Programming Lecture 13

G52CPP C++ Programming Lecture 13 G52CPP C++ Programming Lecture 13 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture Function pointers Arrays of function pointers Virtual and non-virtual functions vtable and

More information

More Advanced Class Concepts

More Advanced Class Concepts More Advanced Class Concepts Operator overloading Inheritance Templates PH (RH) (Roger.Henriksson@cs.lth.se) C++ Programming 2016/17 146 / 281 Operator Overloading In most programming languages some operators

More information

C++ Programming. Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis

C++ Programming. Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis C++ Programming Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis michail.lampis@dauphine.fr Classes These (and the previous) slides demonstrate a number of C++ features related

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started Handout written by Julie Zelenski, Mehran Sahami, Robert Plummer, and Jerry Cain. After today s lecture, you should run home and read

More information

Where do we go from here?

Where do we go from here? Where do we go from here? C++ classes and objects, with all the moving parts visible operator overloading templates, STL, standards, Java components, collections, generics language and performance comparisons

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

Programming in C++: Assignment Week 3

Programming in C++: Assignment Week 3 Programming in C++: Assignment Week 3 Total Marks : 20 August 6, 2017 Question 1 What is the output of the sizeof operator for t in the following code snippet? sizeof(int) = 4) Mark 1 (Assume #include

More information

Overloaded Operators, Functions, and Students

Overloaded Operators, Functions, and Students , Functions, and Students Division of Mathematics and Computer Science Maryville College Outline Overloading Symbols 1 Overloading Symbols 2 3 Symbol Overloading Overloading Symbols A symbol is overloaded

More information

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

the gamedesigninitiative at cornell university Lecture 7 C++ Overview Lecture 7 Lecture 7 So You Think You Know C++ Most of you are experienced Java programmers Both in 2110 and several upper-level courses If you saw C++, was likely in a systems course Java was based on

More information

Static Methods. Why use methods?

Static Methods. Why use methods? Static Methods A method is just a collection of code. They are also called functions or procedures. It provides a way to break a larger program up into smaller, reusable chunks. This also has the benefit

More information

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell

More information

These are notes for the third lecture; if statements and loops.

These are notes for the third lecture; if statements and loops. These are notes for the third lecture; if statements and loops. 1 Yeah, this is going to be the second slide in a lot of lectures. 2 - Dominant language for desktop application development - Most modern

More information

CS 376b Computer Vision

CS 376b Computer Vision CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves

More information

Variables. Data Types.

Variables. Data Types. Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting

More information

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer May 13, 2013 OOPP / C++ Lecture 7... 1/27 Construction and Destruction Allocation and Deallocation Move Semantics Template Classes Example:

More information

CS11 Introduction to C++ Fall Lecture 6

CS11 Introduction to C++ Fall Lecture 6 CS11 Introduction to C++ Fall 2006-2007 Lecture 6 Today s Topics C++ exceptions Introduction to templates How To Report Errors? C style of error reporting: return values For C Standard Library/UNIX functions,

More information

GEA 2017, Week 4. February 21, 2017

GEA 2017, Week 4. February 21, 2017 GEA 2017, Week 4 February 21, 2017 1. Problem 1 After debugging the program through GDB, we can see that an allocated memory buffer has been freed twice. At the time foo(...) gets called in the main function,

More information

Starting to Program in C++ (Basics & I/O)

Starting to Program in C++ (Basics & I/O) Copyright by Bruce A. Draper. 2017, All Rights Reserved. Starting to Program in C++ (Basics & I/O) On Tuesday of this week, we started learning C++ by example. We gave you both the Complex class code and

More information

Object orientation. Programming classes. Programming classes

Object orientation. Programming classes. Programming classes Object orientation Computational Physics Lectures: Programming aspects, object orientation in C++ and Fortran Morten Hjorth-Jensen 1,2 Department of Physics, University of Oslo 1 Department of Physics

More information

C++ Constructs by Examples

C++ Constructs by Examples C++ Constructs by Examples Jan Faigl Department of Computer Science Faculty of Electrical Engineering Czech Technical University in Prague Lecture 12 B3B36PRG C Programming Language Jan Faigl, 2018 B3B36PRG

More information