Coding Standards. Coding Standards. Coding Standards. Code Review. Optimization: Making it fast. Correctness

Size: px
Start display at page:

Download "Coding Standards. Coding Standards. Coding Standards. Code Review. Optimization: Making it fast. Correctness"

Transcription

1 Coding Standards Coding Standards. For : COP Object oriented Programming (Using C++) Compile cleanly (no warnings) Use multiple compilers. gcc/icc suites are installed. Makefiles are required for each project. Piyush Kumar Coding Standards Code Review Use of svn is mandatory. (version control) The palest of ink is better than the best memory Don t break the build. The code in the version control system (svn) should always compile. Lot of svn tutorials on the web. ources/svn/index.html x.php/svn_tutorial Re-Read code. More eyes will help make better quality. Read code from good programmers. You ll learn and benefit. It s best to do code reviews in writing, a simple can suffice. Correctness Optimization: Making it fast. Correct is better than fast. Simple is better than complex. Prefer clarity over cuteness. Write code for people first, then machines. Premature optimization is the root of all evil. Don t optimize prematurely. Remember, It is far easier to make a correct program fast than to make a fast program correct. 1/134 (c) pk 1

2 Global variables. Coding Style Minimize global and shared data. Example. You are not allowed to use static keyword in your code (till asked). Information Hiding: Don t expose internal information from an entity that provides an abstraction. Prefer compile and link time errors to run time errors. Use const proactively. Avoid macros. Avoid Magic numbers. Declare variables as locally as possible. Always initialize variables. Coding Style In the end Avoid long functions (Max number of lines in a function = 25). Each line to be less than 80 characters. Make header files self-sufficient. Always write #include guards. Your software should be: Expandable Maintainable Understandable Stable And preferably built/tested/reviewed by more than one person 2/134 (c) pk 2

3 Documentation Generators Doxygen Tutorial For : COP Object oriented Programming (Using C++) A documentation generator is a programming tool that generates documentation intended for programmers (API documentation) or end users (End-user Guide), or both, from a set of specially commented source codes. Piyush Kumar Commenting programs Why? Doxygen is a documentation generator for C++, C, Java, Objective- C, Python, and to some extent PHP, C# and D. Its highly portable. (Windows/unix/linux/mac) KDevelop has builtin support for Doxygen. Doxygen is very useful for maintaining and understanding your own larger projects as well as useful documentation for others who use your code. How? Configuration File For each project that uses Doxygen, you must create a configuration file. doxygen g creates a example configuration file called Doxyfile doxygen [configfile] will create the documentation for your code as per your configuration specs. Well documented, you just need to fill in the blanks. Main things to set PROJECT_NAME = MyProject OUTPUT_DIRECTORY =./doc INPUT =./src./include FILE_PATTERNS = *.cpp *.hpp GENERATE_HTML = YES EXTRACT_ALL = YES 3/134 (c) pk 1

4 Documenting the source. Documenting the source. HTML allowed Beginning of file: /*! \file dpoint.hpp \brief d-dimensional point class A d-dimensional point class which is written carefully using templates. It allows for basic operations on points in any dimension. Orientation tests for 2 and 3 dimensional points are supported using <a href=" code. This class forms the building block of other classes like dplane, dsphere etc. \author <a href=" Kumar</a> \bug No known bugs. */ Beginning of function. /*! \brief Prints character ch at the current location * of the cursor. * * If the character is a newline ('\n'), the cursor should * be moved to the next line (scrolling if necessary). If * the character is a carriage return ('\r'), the cursor * should be immediately reset to the beginning of the current * line, causing any future output to overwrite any existing * output on the line. If backsapce ('\b') is encountered, * the previous character should be erased (write a space * over it and move the cursor back one column). It is up * to you how you want to handle a backspace occurring at the * beginning of a line. * * \param ch the character to print * \return The input character */ int putbyte( char ch ); Creating the frontpage Example that creates first page of documentation: (You can add it to the main.cpp or main source code file) COP 3330 Project Me and Myself Here you should tell us about how your project works. How to run, any special things you have, etc. Also, explain any non-trivial design decisions you make. If you are working with a partner, clearly State what is each person s contribution. You should also comment on the stability of your code. Any big bugs should be listed here. Basically, anything that you think we need to know in general about your project should go here. Any additional comments you want to make can go here. Did you like the project? Was it too hard, too easy? My TA smells bad. Well, you get the idea. This initial documentation here should be removed. Or else you loose points. Documentation Rules. Each file/function should have a header block. Use descriptive and meaningful names for variables, constants, and functions. Don't just re-express the algorithm in English; tell us why you're doing something. Right: For each name in the array, extract the lastname. Wrong: Set i to 0. Loop from 0 to 10. Call strchr() on a[i], looking for the first ' ' character. Return the pointer the character immediately following the ' '. */ Documentation Rules For each project, create a directory structure like this: prj_?\ Doxyfile Makefile README bin\ data\ doc\ include\ src\ Created using doxygen g Modify it after creation. Sample project: 4/134 (c) pk 2

5 Setting up svn SVN Tutorial For : COP Object oriented Programming (Using C++) Once you receive teamxy.cer Save it in ~/svncert directory Run /tmp/bin/svncertinstall [Read the ed instructions] Run svn ls lists all files in your repository. (empty) Piyush Kumar svn mkdir/rm $ svn mkdir file://svn.cs.fsu.edu/repos/team1/prj_1 -m "Create project directory" Committed revision 1. $ svn ls file://svn.cs.fsu.edu/repos/team1 prj_1 $ svn rm file://svn.cs.fsu.edu/repos/team1/prj_1 -m Delete project directory Remark: The -m flag is used to give a log message for the action. Log messages are enforced by svn. svn importing projects piyush@linprog4.cs.fsu.edu:~/cop3330/prj_1>ls -la total 132 drwx piyush CS-Faculty 4096 Aug 30 22:08. drwx piyush CS-Faculty 4096 Aug 30 22:08.. drwx piyush CS-Faculty 4096 Aug 30 22:08 bin drwx piyush CS-Faculty 4096 Aug 30 22:08 data drwx piyush CS-Faculty 4096 Aug 30 22:08 doc -rw piyush CS-Faculty Aug 30 22:08 Doxyfile drwx piyush CS-Faculty 4096 Aug 30 22:08 include -rw piyush CS-Faculty 96 Aug 30 22:08 Makefile -rw piyush CS-Faculty 39 Aug 30 22:08 README drwx piyush CS-Faculty 4096 Aug 30 22:08 src piyush@linprog4.cs.fsu.edu:~/cop3330>svn import /home/faculty/piyush/ cop3330/prj_1/ -m 'Initial import' svn importing projects piyush@linprog4.cs.fsu.edu:~/cop3330>svn import /home/faculty/piyush/ cop3330/prj_1/ -m 'Initial import' Adding Adding Adding Adding Adding Adding Adding Adding Adding Adding Adding /home/faculty/piyush/cop3330/prj_1/include /home/faculty/piyush/cop3330/prj_1/include/example.hpp /home/faculty/piyush/cop3330/prj_1/doxyfile /home/faculty/piyush/cop3330/prj_1/doc /home/faculty/piyush/cop3330/prj_1/src /home/faculty/piyush/cop3330/prj_1/src/main.cpp /home/faculty/piyush/cop3330/prj_1/src/makefile /home/faculty/piyush/cop3330/prj_1/bin /home/faculty/piyush/cop3330/prj_1/data /home/faculty/piyush/cop3330/prj_1/readme /home/faculty/piyush/cop3330/prj_1/makefile Committed revision 6. piyush@linprog4.cs.fsu.edu:~/cop3330/prj_1> Cleaning and checking out. piyush@linprog4.cs.fsu.edu:~/cop3330/prj_1>cd.. piyush@linprog4.cs.fsu.edu:~/cop3330>rm -rf prj_1/ piyush@linprog4.cs.fsu.edu:~/cop3330>svn co /team1/prj_1/ A prj_1/doxyfile A prj_1/include A prj_1/include/example.hpp A prj_1/doc A prj_1/src A prj_1/src/main.cpp A prj_1/src/makefile A prj_1/bin A prj_1/data A prj_1/makefile A prj_1/readme Checked out revision 6. piyush@linprog4.cs.fsu.edu:~/cop3330>cd prj_1 piyush@linprog4.cs.fsu.edu:~/cop3330/prj_1> 5/134 (c) pk 1

6 The extra.svn Working with the project -la total 132 drwx piyush CS-Faculty 4096 Aug 30 23:02. drwx piyush CS-Faculty 4096 Aug 30 23:02.. drwx piyush CS-Faculty 4096 Aug 30 23:02 bin drwx piyush CS-Faculty 4096 Aug 30 23:02 data drwx piyush CS-Faculty 4096 Aug 30 23:02 doc -rw piyush CS-Faculty Aug 30 23:02 Doxyfile drwx piyush CS-Faculty 4096 Aug 30 23:02 include -rw piyush CS-Faculty 96 Aug 30 23:02 Makefile -rw piyush CS-Faculty 39 Aug 30 23:02 README drwx piyush CS-Faculty 4096 Aug 30 23:02 src drwx piyush CS-Faculty 4096 Aug 30 23:02.svn piyush@linprog4.cs.fsu.edu:~/cop3330/prj_1> $ svn add src/class.h src/class.cpp A src/class.h A src/class.cpp $ svn commit m Added two files Working with the project Checkout a fresh copy of the project every time you start working. Edit/change it. Use svn add/rm commands if you add/delete files to the project Use svn commit command to save your changes (use this often with a meaningful m comment) Working with the project Do not add.o or executable files to the svn server. Only source code. Resources: ources/svn/index.html Project Submission The submission script automatically checks out projects from your directory at the deadline time. Always keep your svn directory compilable. Do not check in anything that does not compiles. 6/134 (c) pk 2

7 Compiling programs Make Tutorial For : COP Object oriented Programming (Using C++) Single source file code: g++ -g Wall main.cpp lm o main Multiple sources [a,b] g++ -g c Wall a.cpp g++ -g c -Wall b.cpp g++ -g o main a.o b.o -lm Piyush Kumar Compiler flags Compilation -c Separate compilation flag. Will produce a ``.o'' file only, without linking. -g The application will have full debug capabilities, but almost no optimization will be performed on the application, leading to lower performance. -Wall Enable all warnings. -o filename Write output to file. For more options: man g++ Multi stage process g++ -g main.cpp lm o main g++ -g -c main.cpp o main.o g++ -g main.o main Compiling and Linking Compilation : Produces object code (main.o) Linking : Produces executable by linking a collection of object files and libraries. A Typical Software Project Make Has 10s to 100s of source files Multiple directories Multiple authors Flags : Differ with compilation Debugging flags (-g) Optimization flags (-O6 malign-double) Release Vs Test builds. Make: A tool to automate the build process. Other cool build tools: CMake, automake/autoconf, scons. Make is not tied to any particular language. Make figures out automatically which files it needs to update, based on which source files have changed. Make enables the end user to build and install your package without knowing the details of how that is done. 7/134 (c) pk 1

8 Make and Makefiles An example make command reads makefile in the current directory for instructions for the build process. If you want to give it a specific file for input, say Makefile-1 use make f Makefile-1 Main.cpp Uses functions from other source files and is the main program. Hello.cpp Function definition. Sumof.cpp Function definition. Functions.hpp Function declarations. Download code from: Use tar zxf makex.tar.gz to untar files. An Example: Makefile-0 An Example: Makefile-0 Running Make make -f Makefile-0 g++ main.cpp hello.cpp sumof.cpp -o hello make <reads default: Makefile> The basic makefile is composed of rules : target: prerequisites <tab> system command Makefile-0 all: <tab> g++ main.cpp hello.cpp sunof.cpp -o hello Other targets Or source files Default target for makefiles make f Makefile-0 and make f Makefile-0 all are equivalent. Targets, Prereqs and commands Target: is usually the name of a file that is generated by a program; examples of targets are executable or object files. A target can also be the name of an action to carry out, such as `clean' A prerequisite is a file that is used as input to create the target. A target often depends on several files. A command is an action that make carries out. Put a tab before the command Command Another Example: Makefile-1 Makefile-1 all: hello hello: main.o sumof.o hello.o g++ main.o sumof.o hello.o -o hello main.o: main.cpp g++ -c main.cpp sumof.o: sumof.cpp g++ -c sumof.cpp hello.o: hello.cpp g++ -c hello.cpp clean: rm -rf *o hello *.exe Dependencies Prerequisites / Dependencies. Wildcards. make f Makefile-1 clean cleans up your directory except source code. 8/134 (c) pk 2

9 Make Another Example: Makefile-2 Only makes out of date prerequisites. Makefile-2 Comments in makefile. hello: main.o sumof.o hello.o g++ main.o sumof.o hello.o -o hello How to decide whether hello is out of date? It is out of date if it does not exist, or if either main.o, sumof.o or hello.o are more recent than it. Variables Using Variables # The variable CC will be the compiler to use. CC=g++ # CFLAGS will be the options I'll pass to the compiler. CFLAGS=-c -Wall -g all: hello hello: main.o sumof.o hello.o $(CC) main.o sumof.o hello.o -o hello main.o: main.cpp $(CC) $(CFLAGS) main.cpp sumof.o: sumof.cpp $(CC) $(CFLAGS) sumof.cpp hello.o: hello.cpp $(CC) $(CFLAGS) hello.cpp If hello is out of date, make executes the command g++ main.o clean: rm -rf *o hello *.exe Makefile targets Make: How does it work? Expected targets in makefiles make all Compile everything. make install Install your software. make clean Clean intermediate files and executables. make reads the makefile in the current directory and begins by processing the first rule. (in our case: all) but before make can fully process this rule, it must process the rules for the files that all depends on, which in this case are the object files. Each of these files is processed according to its own rule. Make: How does it work? Make: Wrap up For any rule, the recompilation must be done if the prerequisites are more recent than the target, or if the target/object file does not exist. make j2 Uses 2 processors for the build process. More info: ml_node/index.html man make Example : 30/examples/makex.tar.gz 9/134 (c) pk 3

10 Administrative Trivia C++ Tour For : COP Object oriented Programming (Using C++) About me: Piyush Kumar Phone: piyush@cs.fsu.edu Office hours: Tuesday 4:30 to 5:30. TAs: Ryan Walega and Yuhua Zhu Piyush Kumar More details on the course information sheet. Your ID Announcement You have been assigned an ID on the Blackboard. You should know your ID. Your ID will be used to setup your Subversion (svn) repository. First Quiz : On Thursday. Will test your background knowledge. Revise your previous C/C++ material. Your first assignment will be posted on Wednesday. Will be due on Tuesday, 9/5/06. You are required to setup your svn repository by this Thursday. The submission will use the svn server. Announcement Blackboard Discussions already setup. Make sure you submit the pre-req form today before you leave. SVN generation of certificates (demo). C++ Tour 10/134 (c) pk 1

11 Why learn C++? C++ Features Ubiquitous Object Oriented Easier large scale projects Resuability High Performance Supports data security Prevents accidents with data Helps code reuse. Lets you use operators the way you like. Allows multiple functions/operators with the same name. When to use C++? When not to use C++? Large projects System applications Graphics Data Structures Speed is an issue? Changes in functionality required. Need exceptions and error handling? Want to speed up your scripts? Small system programs. Fast prototyping. Web-based applications (Perl/Python) Important definitions Algorithm: Ordered set of actions to accomplish a certain task. Program: Implementation of algorithms. Compiler, function, library, bug. Variables, constants. Keywords (if, while, for, ) Data Types. (long, int, ) Compiling/Running programs Single source file code: g++ -g Wall simple.cpp o simple Compilation / Editing Demo Editors: vim / xemacs Xemacs tutorial: hanson.geog.udel.edu/cmg/handouts/xema int main() cs_tutorial.pdf return 0; Vi/vim tutorial : /tutorial.html 11/134 (c) pk 2

12 simple.cpp int main() // Function Declaration // Function body follows simple.cpp On Unix: echo $? On Windows: echo %ERRORLEVEL% // Block of statements begins. return 0; // Block ends. Simple.s System dependent (using g++ -O S simple.cpp).file simple.cpp".def main;.scl 2;.type 32;.endef.text.align 2.p2align 4,,15.globl _main.def _main;.scl 2;.type 32;.endef _main: pushl %ebp ; Save base pointer movl $16, %eax movl %esp, %ebp ; Set up stack frame for debugger subl $8, %esp ; Save space on the stack andl $-16, %esp ; Align stack pointer call alloca ; Platform dependent call call main ; Platform dependent call leave ; free space, pop ebp, esp xorl %eax, %eax ; zero eax ret ; return control to calling procedure. Simple.s (using VC++ 05 compiler) // push ebp mov ebp,esp sub esp,0c0h push ebx A push esi B push edi C lea edi,[ebp-0c0h] mov ecx,30h mov eax,0cccccccch C rep stos dword ptr es:[edi] // return 0; E xor eax,eax // pop edi pop esi pop ebx mov esp,ebp pop ebp ret G++ Compilation. preprocessing (to expand macros) Try cpp simple.cpp > simple.i compilation (from source code to assembly language) Try g++ -Wall S simple.i assembly (from assembly language to machine code) Try as simple.s -o simple.o linking (to create the final executable) Try gcc simple.o Equivalent to ld -dynamic-linker /lib/ld-linux.so.2 /usr/lib/crt1.o /usr/lib/crti.o /usr/lib/gcclib/i686/3.3.1/crtbegin.o -L/usr/lib/gcc-lib/i686/3.3.1 hello.o -lgcc -lgcc_eh -lc -lgcc -lgcc_eh /usr/lib/gcclib/i686/3.3.1/crtend.o /usr/lib/crtn.o $ file./a.exe Identify type of file generated (gcc on windows)../a.exe: PE executable for MS Windows (console) Intel bit Introduction to C++ 12/134 (c) pk 3

13 Organization C++ is a superset of C. C++ = C + objects + Main Theme : Objects Class Vs Object Data Hiding and Abstraction Encapsulation Inheritance Operator and Function Overloading Polymorphism. Generic Programming Features present in C are also present in C++ C++ is a object oriented programming language ( C++ = c + objects + ) OOP is about objects which contain data and functions to manipulate that data. A single unit that contains data and functions that operate on the data is called an object. Main Theme: objects OOP C++ enables you to focus on discrete objects that contain both data and functions to manipulate that data. Instead of data and functions as separate entities as was the case in C. Application = Collection of Objects. Makes complex programs easy to code. Based on concept of objects and classes. Objects: Represent entities with related state and behaviour Instances of a class Classes: Define common characteristics of similar objects. Objects/Classes Object / Class Example Objects are reusable self-contained programming modules with data and functions. Classes are blue-print for objects with common properties, attributes, operations and behaviors. Car Class Attributes: Manufacturer Model Color Engine Behavior: Accelerate Break Steer Tune Up The principal building blocks of OO programs are classes and objects. Objects: Instantiations of classes. 13/134 (c) pk 4

14 Another Object / Class example class Point int _x, _y; // point coordinates // begin interface section ; void setx(const int val); void sety(const int val); int getx() return _x; int gety() return _y; Fundamental building block of OOP: A Class A class defines a data type, much like a struct would be in C. A class is a source code for an object (hence it has both data+member functions) Attributes Point tpoint; // defines an object tpoint class Methods Fundamental building block of OOP: A Class You can imagine that int is a class that has member functions called operator++, etc. An object usually means an instance of a class After the declaration int i; we say that "i is an object of type int." Data Hiding Objects contain information Only part of the information contained in the object might be presented to the user. Rest is concealed. Engine Interface Data Hiding Internal dynamics are not visible to the user. Data hiding is done by using the private keyword in the class definition. Engine Interface Data Hiding Allows data to be accessed by certain functions class Point // private // concealed info int _x, _y; // point coordinates // begin interface section ; void setx(const int val); void sety(const int val); int getx() return _x; int gety() return _y; Point tpoint; // defines an object tpoint tpoint._x = 5; // ILLEGAL 14/134 (c) pk 5

15 Data Abstraction Data Encapsulation DA is a programming technique where one separates the interface from the implementation Class designer worries about the implementation Programmers only need to know the interface. Combine lower level elements to form a new higher level entity. Grouping of attributes and behaviors to form an object. C++ vector type is an example of both data abstraction and Data encapsulation String s; s.rfind( \ ); OOP : Inheritance Inheritance Many classes have common attributes. These classes can be arranged in a hierarchy. Inheritance enables you to reuse code and add data and functionality without making any changes to the existing code. For example, objects can inherit characteristics from other objects. Children inherit traits from their parents. When a class is inherited all the functions and data member are inherited, although not all of them will be accessible by the member functions of the derived class. Inheritance Inheritance protected/public members of the base class are accessible to the derived class private members are not. Derived classes are specialized form of their base class. Abstract class : A base class that is undefined and unimplemented. class vehicle protected: char colorname[20]; int number_of_wheels; vehicle(); ~vehicle(); void start(); void stop(); void run(); ; Super class or Base class class Car: public vehicle protected: char type_of_fuel; Car(); ; Subclass or derived class 15/134 (c) pk 6

16 Multiple definitions? Operator Overloading C++ allows for the same function (or overloaded operator) to have multiple defintions. Swap(int& I, int& j); Swap(string& I, string& j); Swap(double& I, double& j); a.k.a. Function overloading. C++ gives you the power to define operators on user defined types. Example: MyMatrix m = m1 + m2; // cant do this in C. Overloading is a type of polymorphism. Not all operators can be overloaded in C++. Polymorphism MyShape Methods: Draw() Erase() Polymorphism MyShape Methods: Draw() Erase() 2DShape 3DShape 2DShape 3DShape Circle Square Triangle Sphere Cube Tetrahedron Circle Square Triangle Sphere Cube Tetrahedron Base Class MyShape establishes the common interface to anything inherited from MyShape. All shapes can be drawn and erased. Overriding: When a child class extends the functionality of its parent class. Polymorphism allows the programmer to implement different draw/erase methods for derived classes. Sphere and Cube have the same function draw() with different functionality. Polymorphism MyShape Methods: Draw() Erase() Polymorphism 2DShape 3DShape Circle Square Triangle Sphere Cube Tetrahedron No matter what shape the object is, one can use the draw method to draw it correctly. Using operators and functions in different ways depending on what they are operating on is called polymorphism. Static Dynamic The concept builds upon encapsulation and inheritance. 16/134 (c) pk 7

17 Generic Programming Type independent code Write code for one generic type and use it for multiple types. Without Generic Programming: void swap(int & x, int & y) int tmp = x; x = y; y = tmp; void swap(long & x, long & y) long tmp = x; x = y; y = tmp; With Generic Programming template <typename T> void swap(t & x, T & y) T tmp = x; x = y; y = tmp; 17/134 (c) pk 8

18 Basic and Library Types For : COP Object oriented Programming (Using C++) Basic C++ Types integer data-types : char, short, int, long, unsigned char, unsigned short, floating point data-types : float, double, long double logical data-type : bool bool constants : true, false character data-type : char and wchar_t Char constants in single quotes : a text data-type : string string constants in double quotes : Hello world Piyush Kumar Basic C++ Types Recommended assignments: 2.4/2.7/2.8/2.9 Basic Arithmetic types void Return type for a function with no return value void pointers unsigned and signed integers unsigned char x = -1;? unsigned short int x = -1;? Type char short int long float double Low x x High x x Digits of Precision Bytes Wrap around effect. Machine dependent. long double 3.4x x Variable Naming Hungarian naming Read about hungarian naming: on n.html er_technology/hungnote.html Use them in your next assignment onwards. Three parts Base Type One or more prefixes Qualifier 18/134 (c) pk 1

19 Hungarian Base Types Prefixes Specifies the type of the variable being named Not for predefined types Example: wn = Window scr = Screen fon = Font pa = Paragraph Example: WN wnmain=null; FONT fonuserselected = TIMES_NEW_ROMAN; Go in front of the base type Somewhat standard list: a = Array c = Count d = Difference e = Element of an array g = Global variable h = Handle i = index to array m = Module-level variable p(np, lp) = Pointer (near or long) Describes how the variable will be used. Examples Array of windows: awndialogs Handle to a window: hwnmywindow Number of fonts: cfon Qualifiers More Examples The rest of the variable name in case you were not using Hungarian naming. bbusy : boolean capples : count of items dwlightyears : double word fbusy : boolean (flag) isize : integer fpprice: floating-point dbpi: double pfoo : pointer rgstudents : array, or range szlastname : zero-terminated string u32identifier : unsigned 32-bit integer m_nwheels : member of a class, integer Variables What you should know? Machine level representation of built in types. Difference between : a and a Type of every entity in our program should be known to the compiler. Variables Declaration extern int i; Definition int i; Is also a declaration Type specifier 19/134 (c) pk 2

20 Variable Initialization Direct initialization float funity (1.0); Recommended Exercises: 2.15/2.16 Can be more efficient for general classes. std::sting all_nines(10, 9 ); // #include <string> Happens when a variable is created and gives the variable its initial value. Copy initialization float funity = 1.0; Assignment involves replacing the current value of the variable with a new one. Coding Standards Always initialize your variables Define variables where they are used. Pick names carefully. Be careful about scopes of variables Global Scope Local Scope Statement scope More on this when we do class in detail. Const Qualifier Const qualifier for (int Index = 0; Index < 512; ++Index) const int ibufsize = 512; ibufsize = 0; // error: attempt to write to const object const int I, j = 0; What is wrong? Const objects are local to a file by default. Prefer const to #define Using const instead of #define allows much better type checking and reduces name space pollution. Const member functions Specify which member functions can be invoked on const objects. Class Rational const int numerator(void); const Rational operator+(const Rational& rhs) const; const Rational operator+(const Rational& lhs, const Rational& rhs); Const qualifier Const qualifier Const member functions Specify which member functions can be invoked on const objects. Class Rational const int numerator(void); const Rational operator+(const Rational& rhs) const; Rational a,b,c; a = b+c; But does not allow (a+b) = c; Const member functions Specify which member functions can be invoked on const objects. const Rational operator+(const Rational& lhs, const Rational& rhs); When operator+ is a member function, a = b+c is allowed, but what if you want to do a = c + 2; a = 2 + c; Mixed mode operations are the reason why operators are usually defined outside the class. 20/134 (c) pk 3

21 References What is a reference? An alternate name for an object. Frequently used for pass by reference. void swap(int& i, int& j) int tmp = i; i=j; j=tmp; int main() intx,y;... swap(x,y);... References A reference is an alias. Int ival = 1024; int &refval = ival; refval += 2; // increases ival. Errors: int &refval2 = 10; // a reference must be initialized. Int &refval3; Here i and j are aliases for main's x and y respectively. In other words, i is x not a pointer to x, nor a copy of x, but x itself. Anything you do to i gets done to x, and vice versa. Const references A reference that refers to a const object. const int ival = 1024; const int& refval = ival; const double& pi = 3.14; // only legal for const references Errors: Int &ref2 = ival; // Non-const reference to a const object. Const references #include <iostream> using namespace std; int main(void) int dval = 100; const int& ref = dval; ref++; return 0; What is wrong? Typedef names Back to the C++ Class Typedef lets us define a synonym for a type. typedef double wages; typedef int exam_score; typedef wages salary; typedef int Pounds, Shillings, Pennies, Dollars, Cents; Variable definitions: wages wage1,wage2; exam_score person1, person2; typedef struct int scruples; int drams; int grains; WEIGHT; typedef class int scruples; int drams; int grains; WEIGHT; The C++ Class Similar to a struct Defines what objects of a class are (what attributes describe them) Usually contains functionality in addition to attributes The Object An instance of a class A variable declared to be of a "class type class member: a component of a class; may be either a data item or a function 21/134 (c) pk 4

22 Class example 2D Point class Write a class to represent a two dimensional point. What data attributes do we need? What operations? Data Position Operations Set Position Get Position Distance from another point Your first class. #ifndef POINT2D_HPP #define POINT2D_HPP class point2d int _x,_y; void setx(const int val); void sety(const int val); int getx(); int gety(); double double_distance(point2d& p); ; typedef Point2D Cell_tower; typedef Point2D Cell_phone; // Implementation goes here Include guards Private Interface Using the point2d class Point2D p,q; p.setx(10); p.sety(10); q.setx(0); q.sety(10); Cout << Distance between p and q is << p.distance(q) << endl; #endif Implementing the point2d class. #ifndef POINT2D_HPP #define POINT2D_HPP class point2d int _x,_y; void setx(const int val) _x = val; // Rest of the interface/implementation ; typedef Point2D Cell_tower; typedef Point2D Cell_phone; // Implementation goes here #endif Implementing the point2d class. #ifndef POINT2D_HPP #define POINT2D_HPP class point2d int _x,_y; void setx(const int val) ; // Rest of the interface/implementation ; typedef point2d Cell_tower; typedef point2d Cell_phone; // Implementation goes here void point2d::setx(const int val) _x = val; #endif Can be also implemented in point2d.cpp 22/134 (c) pk 5

23 Headers Always use #include guards Do not define variables or functions in headers except Class definitions Const objects Inline functions Difference between #include <myfile.h> #include myfile.h Header files Header file main program point2d.hpp main.cpp #include point2d.hpp Compiler main.o Linker prj_2 implementation file point2d.cpp Compiler point2d.o Avoiding Multiple Inclusion of Header Files Using the MyTimer class often several program files use the same header file containing typedef statements, constants, or class type declarations--but, it is a compile-time error to define the same identifier twice this preprocessor directive syntax is used to avoid the compilation error that would otherwise occur from multiple uses of #include for the same header file #ifndef Preprocessor_Identifier #define Preprocessor_Identifier.. h. #endif #include timer.hpp MyTimer time_elapsed; // your code goes here cout << time_elapsed; A Problem with #define. #define max(a,b) ((a) > (b)? (a) : (b)) int a = 10, b = 20; max(a,b) max(++a,b) max(++a,b+10) 23/134 (c) pk 6

24 C++ IO C++ IO For : COP Object oriented Programming (Using C++) All I/O is in essence, done one character at a time Concept: I/O operations act on streams (sequences) of ASCII characters Piyush Kumar C++ IO <iostream> vs <cstdio> cout cin standard output stream sequence of characters printed to the monitor standard input stream sequence of characters input from the keyboard both cout and cin are data objects and are defined as classes More type-safe: With <iostream>, the type of object being I/O'd is known statically by the compiler. In contrast, <cstdio> uses "%" fields to figure out the types dynamically. Less error prone: With <iostream>, there are no redundant "%" tokens that have to be consistent with the actual objects being I/O'd. Removing redundancy removes a class of errors. Extensible: The C++ <iostream> mechanism allows new user-defined types to be I/O'd without breaking existing code. Imagine the chaos if everyone was simultaneously adding new incompatible "%" fields to printf() and scanf()?! Inheritable: User defined streams possible. Interactive I/O #include <iostream> Example #include <iostream> Namespaces: They provide a way to avoid name collision. Be careful about using this. input data Keyboard executing program output data Screen using namespace std; int main(void) cout << Hello World ; cout << endl; return 0; Standard IO library for C++. Defines two fundamental types, istream and ostream. cin cout ( type istream ) class ( type ostream ) class Stream: A flow of characters (1 or 2 bytes long). Can flow in and out of Files, strings, etc. 24/134 (c) pk 1

25 Example Example invokes a manipulator function called endl. endl looks something like this: #include <iostream> using namespace std; Ostream object named cout. #include <iostream> using namespace std; ostream& endl( ostream& os) os << '\n'; os.flush(); return os; int main(void) int main(void) cout << Hello World ; cout << endl; return 0; Equivalent to: operator<< (cout, Hello World ); Its calling a friend function of ostream with input data. cout << endl; return 0; Equivalent Compiler statement: std::cout.operator<<( std::endl(std::cout) ); Scope Operator for namespaces. Uses function declaration (approx): ostream& operator<<( ostream&, const char * ) Special Output Characters Stream IO headers \n new line \t tab \b backspace \r carriage return \' single quote \" double quote \\ backslash iostream -- contains basic information required for all stream I/O operations iomanip used for performing formatted I/O with stream manipulators fstream used for performing file I/O operations strstream -- used for performing in-memory I/O operations (i.e., into or from strings in memory) A Stream C++ IO Class hierarchy A flow of characters. ios Buffers: IO to streams goes thru a buffer. C++ allows you change the default behavior of associated buffers. State: Each stream is associated with a state indicating various things like if an error has occurred or not ifstream istream istringstream ostream ostringstream stringbuf ofstream streambuf filebuf 25/134 (c) pk 2

26 C++ IO Class hierarchy C++ IO Hierarchy ifstream ios istream cin istringstream ostream cout ostringstream ofstream streambuf The ios hierarchy defines the interface of the IO system. The streambuf hierarchy defines the implementation of the IO system, mostly provides the facilities of buffering and byte-level I/O stringbuf filebuf Other Predefined Streams cerr - the standard destination for error messages (often the terminal window). Output through this stream is unit-buffered, which means that characters are flushed after each block of characters is sent. clog - like cerr, but its output is buffered. Formatting with predefined streams. Remember: Due to inheritance, anything you learn about formatting IO with predefined streams (cin, cout, clog, cerr) also applies to file IO and string IO. Anything available or defined in the ios class is available everywhere in the IO subsystem. Stream IO Inside ios << (left-shift operator) Overloaded as stream insertion operator >> (right-shift operator) Overloaded as stream extraction operator Both operators used with cin, cout, cerr, clog, and with user-defined stream objects Example cin >> Variable; cout << Variable; clog << Variable; Buffered cerr << Variable; Unbuffered, prints Variable immediately. Note: Variable types are available to the compiler. 26/134 (c) pk 3

27 << operator << operator << is overloaded to work on built-in types of C++. Can also be used to output userdefined types. Other interesting examples: cout << \n ; // newline. cout << 1+2= << (1+2) << endl; cout << endl; // newline. cout << flush; // flush the buffer. Associates from left to right, and returns a reference to its left-operand object (i.e. cout). This enables cascading. Outputs char * type as a string. If you want to print the address, typecast it to (void *). Example: char name[] = cop3330 ; cout << name << static_cast<void *>( name ) << endl; static_cast<void *>( name ) equivalent to ((void *) name) in C except that it happens at compile time. Stream insertion: One char. Input Stream put member function Outputs one character to specified stream cout.put( C'); Returns a reference to the object that called it, so may be cascaded cout.put( C' ).put( '\n' ); May be called with an ASCII-valued expression cout.put( 65 ); Outputs A >> (stream-extraction) Used to perform stream input Normally ignores whitespaces (spaces, tabs, newlines) Returns zero (false) when EOF is encountered, otherwise returns reference to the object from which it was invoked (i.e. cin) This enables cascaded input cin >> x >> y; >> controls the state bits of the stream failbit set if wrong type of data input badbit set if the operation fails Input Stream : Looping while (cin >> fname) >> returns 0 (false) when EOF encountered and loop terminates. Example Program #include <iostream> using std::cout; using std::cin; using std::endl; int main(void) int height = 0, maxheight = 0; cout << "Enter the heights: (enter end of file to end): "; while(cin >> height) if( height > maxheight) maxheight = height; cout << "Tallest person's height = " << maxheight << endl; return 0; 27/134 (c) pk 4

28 Output istream member function: get $./a.exe Enter the heights: (enter end of file to end): Tallest person's height = 89 char ch = cin.get(); Inputs a character from stream (even white spaces) and returns it. cin.get( c ); Inputs a character from stream and stores it in c istream member function: get get (array_name, max_size) ; istream member function: getline (array_name, max_size) char fname[256] cin.get (fname, 256); char fname[256] cin.getline (fname, 256); Read in up to 255 characters and inserts a null at the end of the string fname". If a delimiter is found, the read terminates. The array acts like a buffer. The delimiter is not stored in the array, but is left in the stream. Same as get, except that getline discards the delimiter from the stream. istream member functions: ignore() cin.ignore ( ) ; Discards one character from the input stream. cin.ignore (10) ; Discards 10 characters. cin.ignore(256, \n ); Discards 256 characters or newline, whichever comes first. istream member functions: peek(), putback() char ch = cin.peek ( ) ; Peeks into the stream s next character. cin.putback ( A ) ; Puts A back in the stream. 28/134 (c) pk 5

29 FILE IO Example. Copy File first.txt into second.txt. #include <iostream> #include <fstream> using namespace std; int main(void) ifstream source("first.txt"); ofstream destin("second.txt"); char ch; while (source.get(ch)) destin<<ch; return 0; Slightly modified #include <iostream> #include <fstream> using namespace std; int main(void) ifstream source("first.txt"); ofstream destin("second.txt"); char ch; while (source.peek()!= EOF) source.get(ch); destin.put(ch); return 0; More IO functions read() cin.read(fname, 255); Reads 255 characters from the input stream. Does not append \0. cout.write(fname,255); Writes 255 characters. gcount: returns the total number of characters read in the last input operation. ifstream C++ IO Class Hierarchy Revisited istream cin istringstream ios iostream ostream cout ostringstream ofstream stringstream fstream Another example #include <iostream> #include <sstream> #include <string> using namespace std; int main() int i; string line; while(getline(cin,line)) stringstream sfstream(line); while (sfstream >> i) cout << i << endl; return 0; What if I replace this with istringstream? stringstream operations stringstream strm; stringstream strm(mystring); Initializes strm with a copy of mystring. strm.str(); Returns the content of strm in string format. strm.str(s); Copies the string s into strm. Returns void. 29/134 (c) pk 6

30 Stream Manipulators #include <iomanip> dec, hex, oct, setbase oct, hex, dec Cout << hex << 15; Prints F cout << setbase(16) << 15; Prints F again. Formatting Output - Integers int numstdts = 35533; cout << FSU has" << numstdts << "students." prints FSU has35533students. default field width == minimum required default: what happens when explicit formatting is not specified Formatting Output - Integers p.2 we can specify the field width, or number of spaces used to print a value cout << FSU has" << setw(6) << numstdts << " students." prints FSU has students. function call prints in field width 6, right-justified Formatting Output - Integers p.3 cout << FSU has" << setw(10) << numstdts << " students." prints FSU has students. prints in field width 10, right-justified Formatting Output - Integers p.4 cout << left; // flip to left justification cout << FSU has " << setw(10) << numstdts << "students." prints FSU has students. prints in field width 10, left-justified 30/134 (c) pk 7

31 Using the default - Integers p.5 Note on field widths: if a field width specified is too small, or is not specified, it is automatically expanded to minimum required numstdts = 100; cout << FSU has " << numstdts << " students." prints FSU has 100 students. and works for any value of numstdts General Rule of Thumb When you are printing numeric values in sentences or after a verbal label, the default field width usually works well When you are printing numeric values lined up in columns in a table, it is usually necessary to call setw to generate wellformatted output (we will see examples of this later in the course) Formatting Output - Reals float cost = 5.50; cout << "Cost is $" << cost << "today." prints Cost is $5.5today. default large values printed in scientific notation if number is whole, no decimal point numbers of digits not under your control Formatting Output - Reals p.2 Setting up real formatting // use fixed point notation cout << fixed; // print a decimal point (with whole numbers) cout << showpoint; ( noshowpoint ) these remain in effect until changed explicity, as does setprecision. setw only changes next value printed. Formatting Output - Reals p.3 You can just do this, once: float cost = 5.50; cout << "Cost is $" << setw(5) << setprecision(2) << cost << " today." prints Cost is $ 5.50 today. cout << fixed << showpoint << setprecision(2); and these settings will remain in effect throughout your program run if no field width is specified, minimum is used, just as for integers 31/134 (c) pk 8

32 Formatting Output - char default field width == 1 note: setw does have effect on char type data too. char ch = 'Q'; cout << '*' << ch << setw(3) << '*'; prints *Q * Formatting Output - Strings default field width == number of characters in the string can use setw cout << setw(10) << "Hello"; prints Hello Useful Output Spacer const string BLANK = " "; cout << setw(10) << BLANK; prints 10 blanks consider this: const char BLANK = ' '; cout << setw(10) << BLANK; prints 10 blanks! Unitbuf manipulator If you want to flush every output Cout << unitbuf << first << second << nounitbuf; Example Quiz Manipulators: Rolling your own. #include <iostream> #include <iomanip> using namespace std; A. 0.1, 1, e+009 B , , C e-001, e+000, e+009 D , 1.000, E int main() const double tenth = 0.1; const float one = 1.0; const float big = ; cout << "A. " << tenth << ", " << one << ", " << big << endl; cout << "B. " << fixed << tenth << ", " << one << ", " << big << endl; cout << "C. " << scientific << tenth << ", " << one << ", " << big << endl; cout << "D. " << fixed << setprecision(3) << tenth << ", " << one << ", " << big << endl; cout << "E. " << setprecision(20) << tenth << endl; return 0; How to create our own stream manipulators? bell ret (carriage return) tab endline An Example. #include <iostream> #include <ostream> using namespace std; ostream& myendl( ostream& os) os << "test\n"; os.flush(); return os; int main(void) cout << myendl; return 0; Copy not allowed on ostreams. 32/134 (c) pk 9

33 Error states Stream Error States strm::eofbit if (cin.eof() == true) break; // stream end of file. strm::failbit if ( cin.fail() == true) break; // stream format error. strm::badbit If (cin.bad() == true) break; // data lost! Goodbit? cin.good() = ((!eofbit) && (!failbit) && (!badbit)) All eofbit, failbit and badbit should be false. cin.clear() // makes cin good. Error States Example Operators for testing. int ival; While ( cin >> ival,!cin.eof() ) Assert(!cin.bad(), IO stream corrupted ); if (cin.fail()) //bad input cerr << Bad data, try again. ; cin.clear(istream::failbit); // reset the stream continue; // ok to process ival now //end of while. operator! Returns true if badbit or failbit set Useful for file processing if (! readmefile ) cerr << Error ; Interactive Input Interactive Input: Example Write a prompt make it friendly and informative int num; char response; prefix prompt typically contains prefix character to signal point at which to enter input Read value(s) user types data at keyboard cout << "Enter a number -> "; cin >> num; cout << "Enter Y or N -> "; cin >> response; 33/134 (c) pk 10

34 Interactive Input: Contents of Output Window Another C++ Program (Hello argv[1]) Enter a number -> Enter Y or N -> 17<return> Y<return> #include <iostream> using namespace std; int main(int argc, char *argv[]) if (argc!= 2) cout << "Usage: hi.exe <name>" << endl; exit (1); the program will not process the input until the return key is struck cout << "Hello " << argv[1] << endl; return 0; Control structures Statements you should already know : While For If Recommended Assignments: 1.17, /134 (c) pk 11

35 Introduction to the C++ Standard Library. For : COP Object oriented Programming (Using C++) The C++ Standard Library Provides the ability to use: String Types Data Structures (linked list, dynamic arrays, priority queues, binary trees etc) Algorithms (Sorting and Searching ) IO Classes for internationalization support. Piyush Kumar The C++ Standard Library C++ Standard Library Not very homogeneous: String classes are safe and convenient to use (almost self explanatory). The Standard Template Library (STL) optimizes for performance and is not required to check for errors. To use it well, you need to understand the concepts and apply them carefully. Containers Objects that hold/contain other objects. Examples: vector, string Algorithms Work on the containers Examples: sort, search Iterators Provide pointer like interface to containers. Other components Containers Allocators: Provide memory management for containers. Can be customized. Adaptors: A mechanism to make one thing act like another. Example: Stack. Function objects: A function object or a functor, is a construct allowing an object to be invoked or called as if it were an ordinary function, Of course: Contain objects/built in types. More powerful than arrays. Grow (and shrink?) dynamically Manage their own memory Keep track of their size Allow optimal algorithmic operations like scan, sorts etc. 35/134 (c) pk 1

36 Containers Containers Standard STL sequence Containers: vector, string, deque and list Standard non-stl containers: bitset, valarray, priority_queue, queue. Prefer sequential containers to arrays. Use vector by default Use list when there are a lot of insertions/deletions in the middle of the sequence. Use deque when there is a lot of insertion at the beginning or the end of the sequence. data What is a vector? size capacity A contiguous array of elements The first size elements are constructed (initialized) The last capacity - size elements are uninitialized Four data members data pointer size capacity or equivalent allocator allocator data size capacity allocator Sample data layout: Internals. Vector Interface template <class T, class Allocator = allocator<t> > class vector... explicit vector(const Allocator& = Allocator()); explicit vector(size_type n, const T& value = T(), const Allocator& = Allocator());... void reserve(size_type n);... void resize(size_type sz, const T& c = T());... void push_back(const T& x); void pop_back();... iterator insert(iterator position, const T& x); void insert(iterator position, size_type n, const T& x);... iterator erase(iterator position); iterator erase(iterator first, iterator last);... void clear(); ; Vectors Containers : is empty? template <class T, class Allocator = allocator<t> > class vector A default allocator is provided. T is the type of the object stored in the vector. Constructors for vector: vector<int> ivec1; vector<int> ivec2(3,9); vector<int> ivec3(ivec2); Always use: if(icontainer.empty()) Instead of if(icontainer.size() == 0) For some containers, calculating size takes linear time. 36/134 (c) pk 2

37 An example usage An example usage #include <vector> #include <iostream> using namespace std; #include <vector> #include <iostream> using namespace std; int main() vector<int> vec(10); // Creates a vector // Initializes the vector for(int i=0; i< vec.size(); i++) vec[i] = rand() % 10; cout << " vec[" << i << "]=" << vec[i] << endl; ; return 0; pk@linprog4:~>./a.out vec[0]=3 vec[1]=6 vec[2]=7 vec[3]=5 vec[4]=3 vec[5]=5 vec[6]=6 vec[7]=2 vec[8]=9 vec[9]=1 int main() vector<int> ivec; cout << ivec[0]; //error vector<int> ivec2(10); // subscripts available: 0..9 cout << ivec[10]; // error return 0; pk@linprog4:~>./a.out Segmentation fault (core dumped) Make this your friend Iterators Iterators Browsers for containers. Allows restricted access to objects stored in a container. Can be a class, data structure or an Abstract Data Type. A replacement for subscripting, for example in case of vectors: v[i] Subscripts are not available for all containers but iterators are. You can think of an iterator as pointing to an item that is part of a larger container of items. Iterators Container.begin() : All containers support a function called begin, which will return an iterator pointing to the beginning of the container (the first element) Container.end() : returns an iterator corresponding to having reached the end of the container. (Not the last element) Iterators Support the following operations: Operator * : Element at the current position (example: (*it)). You can use -> to access object members directly from the iterator. (Like a pointer) Operator++ : Moves the iterator to the next element. Most iterators will also allow you to use - - for stepping back one element. Operator == and!= : Compare two iterators for whether they represent the same position (not the same element). Operator = : Assigns an iterator. 37/134 (c) pk 3

38 Iterators Iterators Vector iterator picture. v.begin() v.end() data Reason for half-open range: Easy looping Empty containers begin() == end() Defining an iterator: std::class_name<template_parameters>::iterator name; Example: std::vector<int>::iterator vit = myvec.begin(); cout << (*vit) << endl; Printing all elements of a container. std::container_type<template_parameter>::iterator pos; for ( pos = container.begin(); pos!= container.end(); ++pos) cout << (*pos) << endl; Iterators : Examples Iterators: Examples The non-stl way, using subscripts to access data: using namespace std; vector<int> myintvector; // Add some elements to myintvector myintvector.push_back(1); //adds an element to end of vector. myintvector.push_back(4); myintvector.push_back(8); for(int y=0; y<myintvector.size(); y++) cout<<myintvector[y]<<" "; //Should output using namespace std; vector<int> myintvector; vector<int>::iterator myintvectoriterator; // Add some elements to myintvector myintvector.push_back(1); myintvector.push_back(4); myintvector.push_back(8); for(myintvectoriterator = myintvector.begin(); myintvectoriterator!= myintvector.end(); myintvectoriterator++) cout<<*myintvectoriterator<<" "; // Should output Iterator Types Iterators Most Common Input Iterator : read only, forward moves. Output Iterator : write only, forward moves. Forward Iterator: Both read/write with (++) support Backward: Both read/write with (--) support Bi-Directional :Read write and Both ++ or support. Random: Read/Write/Random access. (Almost act like pointers) Type of iterator Input Iterator Output Iterator Bi-directional iterator Random access iterator Example istream_iterator ostream_iterator, inserter, front_inserter, back inserter list, set, multiset, map, multimap Vector, deque 38/134 (c) pk 4

39 Random Access Iterators Allow arithmetic it+n The result will be the element corresponding to the nth item after the item pointed to be the current iterator. it n also allowed (it1 it2) allowed Example: Type of this operation for vectors is defined by vector<t>::difference_type. v.size() v.clear() Back to vectors Iterator type: Random-access Operator [] overloaded v.pop_back() v.push_back( elem ) v.insert(pos,elem) v.erase(pos) Another form: v.erase(bpos,epos) Number of elements in vector Removes all elements Removes last element Adds elem at end of vector Inserts elem at position pos and returns the position of the new element. Removes the element at the iterator position pos and returns the position of the next element. Back to vectors Important facts v.max_size() v.capacity() v.reserve(new_size) v.at( idx ) v.front(), v.back() v.resize(new_size) Maximum number of elements possible (in entire memory!). Returns maximum number of elements without reallocation Increases capacity to new_size. Returns the element with index idx. Throws range error exception if idx is out of range. Returns first, last element. Changes the size to new_size. For vectors, the C++ standard states: &v[i] = &v[0] + I vector < char > vv; vv.push_back ( 'P' ); vv.push_back ( 'Q' ); vv.push_back ( 'R' ); vv.push_back ( '\0' ); printf("%s\n",&vv[0]); Output : PQR The swap trick. Important Facts To trim capacity, you can use the following trick: std::vector<t>(v).swap(v); Makes capacity = size. Example: vector<int>(ivec2).swap(ivec2); When deleting containers of newed/malloced elements, remember to delete/free them before deleting the container. Thread safety of STL containers: Multiple readers are ok Multiple writers to different containers are ok. 39/134 (c) pk 5

40 What can a container contain? Minimal constraint on elements of a container. Operator= a = b; should be valid A copy constructor YourType b(a); should be valid Question : Is vector<int&> allowed? Suggestions Prefer vector and string to dynamically allocated arrays. Use reserve() to avoid unnecessary reallocations. Avoid using vector<bool> Algorithms Methods that act on containers (may or may not change them) Examples: Sorting, searching, reversing etc. Examples: sort(v.begin(), v.end()) pos = find(v.begin(), v.end(), 3) // returns an iterator in the container. reverse(v.begin(), v.end()) unique(v.begin(), v.end()) // operates on a sorted range to collapse duplicate elements. Understand Complexity Example: Vector Insert What happens when the vector is large? Intro To The Standard string Class C++ has a standard class called "string" Strings are simply a sequence of characters Note: This is not a sufficient definition for a "C-string" A "C-string" is an array of characters terminated by a null byte Must #include <string> using the standard namespace to get C++ standard string functionality Note: This is different from #include'ing <string.h> which is the header required for "C-string"s string variables are used to store names, words, phrases, etc. Can be input using ">>" and output using "<<" as other types Some string Functionality Declaring a string: string lastname; firstname[5] = h firstname[6] is undefined unlike C where its \0. string firstname( Piyush ); //Note: String literal enclosed in double quotes string fullname; Assigning a string: lastname = Kumar ; //The usual assignment operator Appending one string on the end of another: fullname = firstname + lastname; //Results in PiyushKumar" fullname = firstname + " " + lastname; //Results in Piyush Kumar" Accessing individual characters in a string: mychar = firstname[4]; //Results in s' (no bounds checking) mychar = firstname.at(4); //Results in s' (does bounds checking) Appending a character to the end of a string: lastname = lastname + mychar; //Results in Kumars" Determining number of characters in string: myint = firstname.length(); //Results in 6 40/134 (c) pk 6

41 string Example #1 Constructors Length of Drew is: 4 Length of Morgan is: 6 Length of DrewMorgan is: 10 #include <iostream> #include <string> Length of Morgan is: 6 using namespace std; Length of Drew Morgan is: 11 int main(void) Length of Morgan is: 6 string first; string last("morgan"); first = "Drew"; //Would be illegal for C-string cout << "Length of " << first << " is: " << first.length() << endl; cout << "Length of " << last << " is: " << last.length() << endl; first += "Morgan"; cout << "Length of " << first << " is: " << first.length() << endl; cout << "Length of " << last << " is: " << last.length() << endl; first.assign("drew"); first.append(" "); first.append(last); cout << "Length of " << first << " is: " << first.length() << endl; cout << "Length of " << last << " is: " << last.length() << endl; return(0); string() // empty string string(string s) // copy of s string(string s, int start) // substring start,end string(string s, int start, int len) // substring string(char* a) // copy of C-string string(int cnt, char c) // one or more chars string(char* beg, char* end) // [beg, end) Additional string Functionality Other overloaded operators Strings can be compared with usual operators >, >= (greater than, greater than/equal to) <, <= (less than, less than/equal to) == (equality) Strings also have a member function called "compare" int string::compare(string rhs); Return value is negative if calling string is less than rhs Return value is positive if calling string is greater than rhs Return value is zero if both strings are identical = is used to assign a value (char, C-string, or string) to a string. += is used to append a string, character, or C-string to a string. + is used to concatenate two strings or a string with something else << and >> are used for input and output. On input, leading whitespace is skipped, and the input terminates with whitespace or end of file. When you need a C-string String Operations string s = 1234 ; s.data() // returns s as a data array, no \0. s.c_str() // returns s as a C-string with \0 int i = atoi(s.c_str()); // conversion // i is now char *carray = new char[80]; s.copy(carray, 79); // copies up to 79 char s.append(s2); // append s2 to s s.push_back(c); // append a char s.erase(various); // erases substrings s.insert(various); // inserts substrings s.clear(); // removes all contents s.resize(cnt); // change the size of s to cnt swap(a, b); // for general containers. 41/134 (c) pk 7

42 String Operations s.replace(various); // replaces characters s.size(); or s.length(); // how many characters? s.max_size(); // maximum number of char? s.empty(); // is s empty? s.reserve(cnt); // reserves memory string Example #2 int main(void) string s1 = "Drew"; string s3; int result; s3 = "Bob"; if (s3 < s1) cout << "oper: s3 less than s1"; if (s3 > s1) cout << "oper: s3 greater than s1"; if (s3 == s1) cout << "oper: s3 is equal to s1"; cout << endl; result = s3.compare(s1); if (result < 0) cout << "comp: s3 less than s1"; else if (result < 0) cout << "comp: s3 greater than s1"; else cout << "comp: s3 is equal to s1"; cout << endl; s3 = "Drew"; if (s3 < s1) cout << "oper: s3 less than s1"; if (s3 > s1) cout << "oper: s3 greater than s1"; if (s3 == s1) cout << "oper: s3 is equal to s1"; cout << endl; result = s3.compare(s1); if (result < 0) cout << "comp: s3 less than s1"; else if (result < 0) cout << "comp: s3 greater than s1"; else cout << "comp: s3 is equal to s1"; cout << endl; return (0); oper: s3 less than s1 comp: s3 less than s1 oper: s3 is equal to s1 comp: s3 is equal to s1 Even More string Functionality Getting a substring of a string: string string::substr(int startpos, int length) Returns the substring starting at "startpos" with length of "length" Finding the location of a substring within a string: int string::find(string lookfor); Returns the index where the first instance of "lookfor" was found in the string Returns "string::npos" (which is usually -1) when the substring isn't found int string::find(string lookfor, int startfrom); Returns the index where the first instance of "lookfor" was found, starting the search at the index "startfrom", or "string::npos" when the substring isn't found Finding specific characters in a string: int string::find_first_of(string charlist, int startfrom); Returns the index of the first instance of any character in "charlist", starting the searc at the index "startfrom", or "string::npos" if none of the chars are found int string::find_first_not_of(string charlist, int startfrom); Returns the index of the first instance of any character NOT in "charlist", starting the search at the index "startfrom", or "string::npos" if none of the chars are found int main() int startpos; int len; int commaloc; int howloc; int loc; int spaceloc; string mystr; string mystr2; string Example #3 mystr = "Hello, how are you?"; startpos = 7; len = 3; mystr2 = mystr.substr(startpos, len); cout << "Substr: " << mystr2 << endl; commaloc = mystr.find(","); howloc = mystr.find(mystr2); cout << "Comma: " << commaloc; cout << " how: " << howloc << endl; cout << "Spaces:"; spaceloc = mystr.find(" "); while (spaceloc!= string::npos) cout << " " << spaceloc; spaceloc = mystr.find(" ", spaceloc + 1); cout << endl; cout << "Punct and spaces:"; loc = mystr.find_first_of(",?", 0); while (loc!= string::npos) cout << " " << loc; loc = mystr.find_first_of(",?", loc + 1); cout << endl; return (0); Substr: how Comma: 5 how: 7 Spaces: Punct and spaces: string Class Implementation The string class uses dynamic memory allocation to be sure segmentation faults don't occur When a string is updated such that it requires more characters than currently allocated, a new, larger array is allocated and the prior contents are copied over as necessary Since dynamic allocation is relatively slow, it is not desirable to be re-allocating strings often C++ allows some memory to be "wasted" by often allocating more space than is really needed However, as strings are appended to the end, it is likely that a re-allocation won't be needed every time Occasionally, re-allocation is necessary and is performed, again allocating more memory than necessary Note: this is all done automatically by the string class ( Similar to vectors? ) Some Final string Functionality Several member functions are available to get information about a string capacity: The number of characters that can be placed in a string without the inefficiency of re-allocating length: The number of characters currently in the string You can manually change the capacity of a string resize: Sets the capacity of a string to be at least a userdefined size This can be useful if you know a string will be at most n characters long By resizing the string to capacity n only that amount of memory is associated with the string This prevents wasted memory when you know the exact size you need Additionally, it can help prevent numerous re-allocations if you will be appending on to the end of the string, but know the final size ahead of time 42/134 (c) pk 8

43 Example #4 int main(void) string str; string str2; cout << "Str: " << str << endl; cout << "Length: " << str.length(); cout << " Cap: " << str.capacity(); cout << endl; str = "888"; cout << "Str: " << str << endl; cout << "Length: " << str.length(); cout << " Cap: " << str.capacity(); cout << endl; Str: Length: 0 Cap: 0 Str: 888 Length: 3 Cap: 31 Str: Length: 8 Cap: 31 Str: Length: 14 Cap: 31 Str: abcdefghijklmnopqrstuv Length: 36 Cap: 63 str += "-111-"; cout << "Str: " << str << endl; cout << "Length: " << str.length(); cout << " Cap: " << str.capacity(); cout << endl; str += "1723-9"; cout << "Str: " << str << endl; cout << "Length: " << str.length(); cout << " Cap: " << str.capacity(); cout << endl; str += "abcdefghijklmnopqrstuv"; cout << "Str: " << str << endl; cout << "Length: " << str.length(); cout << " Cap: " << str.capacity(); cout << endl; return (0); C Vs C++: Strings C Library Functions strcpy strcat strcmp strchr, strstr strrchr strlen C++ string operators /member functions. = += = =,!=, <, >, <=, >=.find( ) method.rfind( ) method.size( ) or.length( ) methods Reading text into a string Char functions in C/C++ getline(istream, s); // Reads from istream (e.g., cin or a file) into the string s. Returns a reference to istream that can be used again. Reads all characters until a line delimiter or end of file is encountered. The line delimiter is extracted but not put into the string You can then parse s without worrying about end of line or end of file characters. #include <ctype.h> int isalnum(int c); //non-zero iff c is alphanumeric int isalpha(int c); //non-zero iff c is alphabetic int isdigit(int c); //non-zero iff c a digit: 0 to 9 int islower(int c); //non-zero iff c is lower case int ispunct(int c); //non-zero iff c is punctuation int isspace(int c); //non-zero iff c is a space char int isupper(int c); // non-zero iff c is upper case int isxdigit(int c); //non-zero iff c is hexadecimal int tolower(int c); //returns c in lower case int toupper(int c); //returns c in upper case Using the transform algorithm #include <algorithm> Lowercase all characters of a string: transform(s.begin(), s.end(), // source s.begin(), // destination tolower); // operation Uppercase all characters: transform(s.begin(), s.end(), s.begin(), toupper); tolower and toupper are C-string functions. Other functions can also be used. Using the transform algorithm #include <algorithm> What does the following do? If (s == reverse(s.begin(),s.end())) cout << S is a ; 43/134 (c) pk 9

44 Solution to assignment 1 Solution to assignment 1 vector<string> vs_inpvec; string s_one_entry; int counter = 0; while( getline( cin, s_one_entry) ) int _pos = s_one_entry.rfind('/'); if(_pos!= -1) s_one_entry = s_one_entry.substr(_pos+1, s_one_entry.size() ); sort(vs_inpvec.begin(), vs_inpvec.end()); int i_inp_elements = vs_inpvec.size(); cout << "Input Elements = " << i_inp_elements << endl; vs_inpvec.erase( unique(vs_inpvec.begin(), vs_inpvec.end()), vs_inpvec.end() ); vs_inpvec.push_back(s_one_entry); What does this code do? int i_unique_elements = vs_inpvec.size(); cout << "Unique Elements = " << i_unique_elements << endl; cout << "Duplicate Elements = " << i_inp_elements - i_unique_elements << endl; Reading assignment: Chapter 3, 9 Including Bitset. #include <bitset> bitset operators Ordered collection of bits. Example program // create a bitset that is 8 bits long bitset<8> bs; // display that bitset for( int i = (int) bs.size()-1; i >= 0; i-- ) cout << bs[i] << " "; cout << endl; // create a bitset out of a number bitset<8> bs2( (long) 131 ); // display that bitset, too for( int i = (int) bs2.size()-1; i >= 0; i-- ) cout << bs2[i] << " "; cout << endl;!= returns true if the two bitsets are not equal. == returns true if the two bitsets are equal. &= performs the AND operation on the two bitsets. ^= performs the XOR operation on the two bitsets. = performs the OR operation on the two bitsets. ~ reverses the bitset (same as calling flip()) <<= shifts the bitset to the left >>= shifts the bitset to the right [x] returns a reference to the xth bit in the bitset. Example // create a bitset out of a number bitset<8> bs2( (long) 131 ); cout << "bs2 is " << bs2 << endl; // shift the bitset to the left by 4 digits bs2 <<= 4; cout << "now bs2 is " << bs2 << endl; Output? bs2 is now bs2 is Recommended Exercise: 3.23, 3.21, 3.18, /134 (c) pk 10

45 Introduction To Pointers Pointers and Arrays For : COP Object oriented Programming (Using C++) A pointer in C++ holds the value of a memory address A pointer's type is said to be a pointer to whatever type should be in the memory address it is pointing to Just saying that a variable is a pointer is not enough information! Generic syntax for declaring a pointer: datatype *pointervarname; Specific examples int *iptr; //Declares a pointer called "iptr" that will //point to a memory location holding an //integer value float *fptr; //Declares a pointer called "fptr" that will //contain an address, which is an address of //a memory location containing a float value Piyush Kumar The Operator & There is an operator, & When this symbol is used as a unary operator on a variable it has a different meaning than as a binary operator or type specifier It is unrelated to the "logical and", which is && or bitwise and, & It is unrelated to the use of & in regards to reference parameters The operator & is usually called the "address of" operator It returns the memory address that the variable it operates on is stored at in memory Since the result is an address, it can be assigned to a pointer int Using The "Address Of" 1000 Operator i = 6; //Declares an int, stored //in memory somewhere //In this example, it is //stored at address 1000 int *iptr; //Declares a pointer. The //contents of this variable //will point to an integer //value. The pointer itself //must be stored in memory, and //in this example, is stored at //memory location i iptr iptr = &i; //Sets the iptr variable to //contain the address of the //variable i in memory The Operator * Like the &, the * operator has another meaning as well The * operator is usually referred to as the "dereference operator" The * operator operates on a pointer value The meaning is "Use the value that this pointer points to, rather than the value contained in the pointer itself" If a pointer is of type "int *" and the dereference operator operated on the pointer, the result is a value of type "int" Dereferenced pointers can be used as L-values or R-values When used as an L-value (on the left side of an assignment), the pointer is unaffected, but the memory that it points to is changed When a pointer that is pointing to memory you are not allowed to access is dereferenced, the result is a program crash via a "segmentation fault" Using The Dereference Operator 6 4 int i = 6; //Declares integer called i int *iptr; //Declares a pointer to an int iptr = &i; //Sets the iptr variable to //contain the "address of" the //variable i in memory cout << "i: " << i << endl; cout << "i: " << *iptr << endl; *iptr = 4; //Changes the memory being //pointed to by iptr to contain //the value 4 cout << "i: " << i << endl; cout << "i: " << *iptr << endl; i: 6 i: 6 i: 4 i: i iptr 45/134 (c) pk 1

46 Arrays And Pointers The name of an array variable in C++, without the use of the [ ] operator, represents the starting address of the array This address can be stored in a pointer variable Since array values are guaranteed to be in contiguous memory, you can access array values using this one pointer Examples of this will come later, after discussing "pointer arithmetic" const int NUM = 3; int iary[num] = 2, 4, 6 ; int *iptr; 1000 NUM 1012 iary[2] iptr = iary; //Assigns iptr to point //to the first integer //in the iary array //This cout prints the value of the //value stored in the location iptr //points to (the first int in the //iary, in this case) cout << "val: " << *iptr << endl; val: iary[0] iary[1] iptr Pointer Arithmetic, Motivation Incrementing the contents of an "int *" variable by one doesn't make sense Integers require 4 bytes of storage Incrementing iptr by 1, results in the pointer pointing to location 1005 However, location 1005 is not an address that is the starting address of an integer Dereferencing a pointer that contains an invalid memory location, such as 1005 may result in a Bus Error When your program results in a bus error, the program crashes immediately (Segmentation fault) NUM iary[0] iary[1] iary[2] iptr Pointer Arithmetic, Description Recall that a pointer type specifies the type of value it is pointing to C++ can determine the size of the value being pointed to When arithmetic is performed on a pointer, it is done using this knowledge to ensure the pointer doesn't point to intermediate memory locations If an int requires 4 bytes, and iptr is a variable of type "int *", then the statement "iptr++;" actually increments the pointer value by 4 Similarly, "iptr2 = iptr + 5;" stores the address "five integers worth" past iptr in iptr2 If iptr was 1000, then iptr2 would contain the address = * 4 Pointer arithmetic is performed automatically when arithmetic is done on pointers No special syntax is required to get this behavior! Using Pointer Arithmetic const int NUM = 3; int iary[num] = 2, 4, 6 ; int *iptr; int *iptr2; int *iptr3; int i; iptr = iary; //Assigns iptr to point //to the first integer //in the iary array iptr3 = iary; for (i = 0; i < NUM; i++) iptr2 = iptr + i; cout << i << " " << iary[i] << " " << *iptr2 << " " << *iptr3 << " " << *(iptr + i) << endl; iptr3++; NUM iary[0] iary[1] iary[2] iptr Other Variables Static Allocation Of Arrays All arrays discussed or used thus far in the course have been "statically allocated" The array size was specified using a constant or literal in the code When the array comes into scope, the entire size of the array can be allocated, because it was specified You won't always know the array sizes when writing source code Consider a program that modifies an image As the developer, you won't know what image size the user will use One solution: Declare the image array to be 5000 rows by 5000 columns Problem #1: This likely wastes a lot of memory if the user uses an image that is 250x250, then there are 24,937,500 unused pixels. If each pixel requires 4 bytes, this is almost 100 MB (megabytes!) of wasted space Problem #2: What if the user needs to edit an image that is 6000x6000? Your program will fail, and likely result in a crash Dynamic Allocation Of Arrays If an array is "dynamically allocated", then space is not reserved for the array until the size is determined This may not be until the middle of a function body, using a value that is not constant or literal The size may be input by the user, read from a file, computed from other variables, etc. As memory is "claimed" using dynamic allocation, the starting address is provided, allowing it to be stored in a pointer variable Since pointers can be used to access array elements, arrays can be dynamically allocated in this way Dynamically allocated memory is claimed from the heap, as opposed to the stack 46/134 (c) pk 2

47 The "new" Operator Static Vs Dynamic Allocation A new operator is used to perform dynamic allocation The operator is the "new" operator The new operator: Attempts to find the amount of space requested from the heap "Claims" the memory when an appropriately sized available chunk of the heap is found Returns the address of the chunk that was claimed "new" can be used to allocated individual variables: iptr = new int; //allocates an int variable "new" can also be used to allocated arrays of variables: iptr = new int[5]; //allocates an array of 5 integers Array elements can be accessed using pointer arithmetic and dereferencing, or via the well-know [ ] operator, indexing an array Stack allocation int intarray[10]; intarray[0] = 6837; Heap allocation int *intarray; intarray = new int[10]; intarray[0] = 6837;... delete[] intarray; Code Stack Heap Dynamic Allocation Of Arrays, Example This fragment lets the user decide how big of an array is needed int i; //Loop variable int *iary; //This will be our array - an int pointer int num; //Length of the array (input from user) cout << "Enter length of array: "; cin >> num; iary = new int[num]; //Dynamically declare an ary. Get //necessary mem, assign address to iary for (i = 0; i < num; i++) cout << "Enter int num " << i << ":"; cin >> iary[i]; //use iary as if it were an array! for (i = 0; i < num; i++) cout << "Index " << i << ": " << iary[i] << endl; Outputs Of Dynamic Allocation Example Enter length of array: 7 Enter int num 0:3 Enter int num 1:1 Enter int num 2:6 Enter int num 3:8 Enter int num 4:3 Enter int num 5:2 Enter int num 6:1 Index 0: 3 Index 1: 1 Index 2: 6 Index 3: 8 Index 4: 3 Index 5: 2 Index 6: 1 Enter length of array: 3 Enter int num 0:8 Enter int num 1:4 Enter int num 2:1 Index 0: 8 Index 1: 4 Index 2: 1 Note: In the left example, the array required 28 bytes of memory (7 * 4). Exactly 28 bytes was allocated for the array. In the right example, the array required only 12 bytes (3 * 4). Exactly 12 bytes was allocated for the array, and no extra memory was unused and wasted. Another Dynamic Allocation Example What is the likely result of the following program fragment? int i; //Loop variable int *iary; //This will be our array - an int pointer int num; //Length of the array (input from user) for (i = 0; i < ; i++) num = 50000; iary = new int[num]; //Call a function to randomly fill the array //Do some sort of processing on the element ary //Do it again and again and again, accumulating stats. Example Problem Description The likely result would be that the program would be a failure The reason is that the new operator claims the memory requested each iteration of the loop There is only a finite amount of memory, though, and the amount requested is likely beyond the amount available The problem is that while the memory is claimed, it is never released, of "freed", or "deleted" If you don't free the memory, but you do change the pointer pointing at it to point to a different address, then: The original memory is still claimed There is no way to access the original memory, since no pointers are pointing to it The chunk of memory is wasted throughout the entire execution of the program This is referred to as a "memory leak", and should be avoided 47/134 (c) pk 3

48 Using The "delete" Operator Dynamically allocated memory can be released back into the available memory store using the "delete" operator The delete operator operates on a pointer and frees the memory being pointed to Recall a pointer may be pointing to a single value, or an array of values Due to this, the delete operator is used differently to delete single values and arrays Deleting a single value being pointed to: delete iptr; Deleting an array of values being pointed to: delete [] iptr; Using the delete operator on a null pointer has no effect Using the delete operator on a pointer pointing to memory that is not currently claimed by your program will cause a segmentation fault Initialize all pointers to 0 (zero) Set all pointers to 0 after using the delete operator on them Fixing The Memory Leak int i; //Loop variable int *iary; //This will be our array - an int pointer int num; //Length of the array (input from user) for (i = 0; i < ; i++) num = 50000; iary = new int[num]; //Call a function to randomly fill the array //Do some sort of processing on the element ary //Do it again and again and again, accumulating stats. delete [] iary; //No need to tell delete the size of //the array. This only frees up the //memory that iary is pointing to. It //does NOT delete the pointer in any way Dynamically Allocating Objects The arrow operator is another operator needed for working with pointers The arrow operator is a dash and a greater than symbol: -> It is used to access public member variables or functions of an object that is being pointed to by a pointer It is used the same way the dot operator is used on an actual object, but the arrow is used on a pointer variable instead The arrow is used for convenience Alternatively, you could deference the pointer and use the dot operator Since the arrow operator implies a dereference, using the arrow operator on a pointer that doesn't point to claimed memory results in a segmentation fault! Using The Arrow Operator -> class CircleClass float x; float y; float z; float radius; ; int main() CircleClass myobj; CircleClass *myptr; myptr = &myobj; myobj.x = 5; myptr->y = 9; myobj.z = 15; myptr->radius = 56.4; I access the same memory location using both the actual object and a pointer to that object. The dot operator is used with the object The arrow operator is used with the pointer... Dynamically Allocating Objects class TempClass int ival; double dval; ; int main() TempClass *temp; //4 bytes (or sizeof(tempclass*) temp = new TempClass; //Claims enough space for all //members of a tempclass object temp->ival = 16; temp->dval = 4.5; Note: The actual object that is allocated (the memory location) never gets a name! It is only pointed to by the temp pointer! //Since temp is a pointer, //the arrow operator is used Using Constructors With Dynamic Allocation Remember a constructor is used whenever an object is allocated, whether statically or dynamically class IntClass int val; IntClass() //Default ctor sets val to 0 val = 0; IntClass(int inval) //Initializes val to value passed in val = inval; ; IntClass ic; //sets ic.val to 0 IntClass *icptr = new IntClass; //sets icptr->val to 0 Uses the default ctor... IntClass ic2(6); //sets ic2.val = 6 IntClass *icptr2 = new IntClass(10); //sets icptr->val to 10 Uses the value ctor 48/134 (c) pk 4

49 The sizeof Operator Often, you need to know how many bytes of memory a variable or type requires. Different architectures use different sizes. Use the sizeof operator to determine the current architecture's size of a var or type int num; //Length of the array (input from user) cout << "sizeof(int): " << sizeof(int) << endl; cout << "sizeof(float): " << sizeof(float) << endl; cout << "sizeof(double): " << sizeof(double) << endl; cout << "sizeof(char): " << sizeof(char) << endl; cout << "sizeof(num): " << sizeof(num) << endl; sizeof(int): 4 sizeof(float): 4 sizeof(double): 8 sizeof(char): 1 sizeof(num): 4 Result may vary on different machines! (These results are common) Dynamically Alloc Mem in C Operators "new" and "delete" don't exist in C, but C programmers still need dynamic allocation. Three important functions for C dynamic allocation //malloc takes one parameter, size, which is simply //the number of bytes you are requesting.. Returns a //void *, which is a generic pointer to any type. void *malloc(size_t size); //calloc initializes each ary element to 0. nelem is //the number of elements you are requesting, and //elsize is the number of bytes each element requires. void *calloc(size_t nelem, size_t elsize); //free takes one param, which is a pointer to memory //that was previously allocated using malloc or calloc void free(void *ptr); Dynamically Alloc Mem in C Example #include <stdlib.h> //--- int *iary; //This will be our array - an int pointer int *iary2; //Another integer array. int num; //Length of the array (input from user) cout << "Enter length of ary: "; cin >> num; iary = (int *)malloc(num * sizeof(int)); //not init. iary2 = (int *)calloc(num, sizeof(int)); //init to 0 //Something useful happens here.. //Free up the memory now! free(iary); free(iary2); Prefer C++ to C string *stringarray1 = static_cast<string *> (malloc(10*sizeof(sting)) ); string *stringarray2 = new string[10]; free (stringarray1); // no destructors called // What happened if string object reallocated stuff? Enlarged itself? delete[] stringarray2; Use same form of new/delete string *stringarray2 = new string[100]; delete stringarray2; // Program behavior undefined // At least the 99 strings are still in the memory somewhere Memory LEAK! new/delete in constructors/destructors For a class with dynamically allocated memory, Initialize pointers in constructors to 0. If unknown size, make them null. Deleting a null pointer is always safe. Make sure you delete them all in the destructor. 49/134 (c) pk 5

50 Out of memory errors #include <iostream> Multidimensional Arrays using namespace std; void OutOfMemory() cerr << "No more memory\n"; abort(); int main() set_new_handler(outofmemory); double *pbigarray = new double[ ]; cout << "I am here\n"; pbigarray[ ] = 123; cout << pbigarray[999999] << endl; return 0; Definition Type MDarray[size_1][size_2]... [size_k] What it means k - dimensional array MDarray: array identifier size_i: a positive constant expression Type: standard type or a previously defined user type and is the base type of the array elements Semantics MDarray is an object whose elements are indexed by a sequence of k subscripts the i-th subscript is in the range 0... size_i-1 Multi-dimensional Arrays Multi-dimensional Arrays Multidimensional arrays are laid out in row-major order Consider int M[2][4]; M is two-dimensional array that consists of 2 subarrays each with 4 elements. 2 rows of 4 elements The array is assigned to a contiguous section of memory The first row occupies the first portion The second row occupies the second portion Art of Assemby website. Multi-dimensional arrays Example: int myimage[nrows][ncols]; Can be used as parameter in a function prototype. Example: void process_matrix( int in[ ][4], int out[ ][4], int nrows) void process_matrix( int in[4][4], int out[4][4], int nrows) //Invalid void process_matrix( int in[][], int out[][], int nrows) Multi-dimensional arrays Really an array of arrays. int main() int x [3][4]; int (*ip)[4]; // pointer to an array of 4 integers int *oip = &(x[0][0]); ip = x; for (int i = 0 ; i < 3; ++i) for (int j = 0; j < 4; ++j) x[i][j] = i*10 + j; cout << (*ip)[0] << "\t" << (* (++ip) )[0] << endl; cout << * (++oip) << endl; return 0; Recommended exercises: 5.9, 5.30, 5.14, /134 (c) pk 6

51 Multi-dimensional Arrays int (*matrix)[10]; Pointer to an array of 10 integers int *matrix[10]; Array of 10 integer pointers. Example: int main( int argc, char *argv[]) argv[0] = prgram name argv[1] =../data/filename argv[2] = 2 Buffer Overflow problems Let A be a string and B be an integer. Changing A could change B! /* overflow.c - demonstrates a buffer overflow */ #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) char buffer[10]; if (argc < 2) fprintf(stderr, "USAGE: %s string\n", argv[0]); return 1; strcpy(buffer, argv[1]); return 0; A A A A A A A A B B Buffer Overflow problems Type conversions Let A be a string and B be an integer. Changing A could change B! /* better.c - demonstrates one method of fixing the problem */ #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) char buffer[10]; if (argc < 2) fprintf(stderr, "USAGE: %s string\n", argv[0]); return 1; strncpy(buffer, argv[1], sizeof(buffer)); buffer[sizeof(buffer) - 1] = '\0'; return 0; A A A A A A A A B B C-Style casts float average = (float) sum / items; float average = (float) (sum/items); C++ Style static_cast< type >( identifier ) float average = static_cast< float >( sum ) / items; float average = sum / static_cast< float >( items ); Type conversions static_cast x=(float) i; x=float(i); x=static_cast<float>(i); i=reinterpret_cast<int>(&x) func(const_cast<int>(c_var)) cast in C++ - C notation cast in C++, functional notation ANSI C++ - recommended ANSI C++, not portable and system dependent where C_var is a const variable Used for removing const-ness when invoking func. Use with care. static_cast<t>(expression) The static_cast<>() is used to cast between the integer types. 'eg' char->long, int->short etc. Static cast is also used to cast pointers to related types, for example casting void* to the appropriate type. BaseClass_Employee* a = new DerivedClass_Manager(); static_cast<derivedclass_manager>(a)->derivedclassmethod(); 51/134 (c) pk 7

52 reinterpret_cast const_cast float f = 2.5f; double * pd = reinterpret_cast<double*>(&f); cout << f << endl << *pd << endl; Outputs (!!!): $./a.exe e+159 Reinterpret cast simply casts one type bitwise to another. Any pointer or integral type can be casted to any other with reinterpret_cast, easily allowing for misuse. static_cast will not be allowed in this case. const_cast<t>(expression) The const_cast<>() is used to add/remove const(ness) of a variable. class A void func() ; void f(const A& a) A& b = const_cast<a&>(a); b.func(); dynamic_cast Type conversions Dynamic cast is used to convert pointers and references at run-time, generally for the purpose of casting cast a pointer or reference up or down an inheritance chain (inheritance hierachy). class Employee... ; class Manager : public Employee... ; void f(employee* a) Manager* b = dynamic_cast<manager*>(a); All Pointers can be converted to void * An explicit cast is required in C++ when you want to convert a void * to another pointer type. char *char_p; void *generic_p;... generic_p=char_p; // OK, char* va in void* char_p=generic_p; // OK in C, illegal in C++ char_p=static_cast<char *> (generic_p); // The C++ way. Implicit conversions char, short and bool are promoted to int Integer types which cannot be represented with an int are promoted to unsigned In an expression with mixed type, lower order operand are promoted to the upper order, with the following rule: int < unsigned < long < unsigned long < float < double < long double bool is an integer type, true is promoted to 1 and false to 0 52/134 (c) pk 8

53 GDB GDB For : COP Object oriented Programming (Using C++) Lot of tutorials on google. Debugging tool, see what happens as your program runs Needs the g flag while compiling This adds additional information (i.e. line numbers) in the binary executable Execution: Invoke by typing gdb <executable name> E.g.: gdb a.out Piyush Kumar Basic Commands Basic Commands quit Quits gdb. Note that it is NOT exit run Run the program; it stops at each break point set by break command x (address) Examine the CONTENTS of the memory at (address) print (expression) Print the value of the expression - can be registers or simple equations break (function name or *memory address) Set breakpoints E.g. : break main break x.cpp:15 continue Resume execution step (s) Step to the next line in CODE. Warning: If you use the step command while control is within a function that was compiled without debugging information, execution proceeds until control reaches a function that does have debugging information. next (n) Similar to step This is similar to step, but function calls that appear within the line of code are executed without stopping. disas Show assembly instructions for the current function Basic Commands where/bt Shows the current line and stack backtrace. Very useful for segmentation faults. info registers Shows the current state of the registers display <var/register> display the contents of the register/var. E.g. : display count display $eax More Commands: Graphical User interface: ddd Screen shots/movies : 53/134 (c) pk 1

54 Exceptions Exceptions For : COP Object oriented Programming (Using C++) Exceptions are run time anomalies, such as division by zero, that require immediate handling when encountered by your program. The C++ language provides built in support for raising and handling exceptions. With C++ exception handling, your program can communicate unexpected events to a higher execution context that is better able to recover from such abnormal events. Useful when the code that detects the problem cannot handle it (Exception Detection code). Control must be transferred to the code that can handle such error. (Exception Handling code). Piyush Kumar Material from 4 th ed. Programming and Problem solving with C++, Dale, Weems. Exceptions in C++ Communication between exception detection and exception handling parts of the program in C++. It involves: throw expressions try blocks exception classes The try, throw, and catch statements implement exception handling. Exceptions in C++ If not handled properly, exceptions can cause the program to : Crash Falls into unknown state An exception handler is a section of program code that is designed to execute when a particular exception occurs Resolve the exception Lead to known state, such as exiting the program Standard Exceptions Exceptions Thrown by the Language new Standard Library Routines User code, using throw statement The throw Statement Throw: to signal the fact that an exception has occurred; also called raise Syntax throw Expression 54/134 (c) pk 1

55 The try-catch Statement How one part of the program catches and processes the exception that another part of the program throws. TryCatchStatement try Block catch (FormalParameter) Block catch (FormalParameter) FormalParameter DataType VariableName Example of a try-catch Statement try // Statements that process personnel data and may throw // exceptions of type int, string, and SalaryError catch ( int ) // Statements to handle an int exception catch ( string s ) cout << s << endl; // Prints "Invalid customer age" // More statements to handle an age error catch ( SalaryError ) // Statements to handle a salary error Execution of try-catch A statement throws an exception Control moves directly to exception handler Exception Handler Statement following entire try-catch statement No statements throw an exception Statements to deal with exception are executed void Func3() try Throwing an Exception to be Caught by the Calling Code Func4(); catch ( ErrType ) Function call Normal return void Func4() Return from thrown exception if ( error ) throw ErrType(); Practice: Dividing by ZERO Apply what you know: int Quotient(int numer, // The numerator int denom ) // The denominator if (denom!= 0) return numer / denom; else //What to do?? do sth. to avoid program //crash A Solution int Quotient(int numer, // The numerator int denom ) // The denominator if (denom == 0) throw DivByZero(); //throw exception of class DivByZero return numer / denom; 55/134 (c) pk 2

56 A Solution // quotient.cpp -- Quotient progra m #include<iostrea m > #include <string> using namespace std; int Quotient(int,int); class DivByZero // Exception class ; intmain() intnumer; // Numerator intdenom; // Deno minator cout << "Enter numerator and denominator:"; cin >> numer >> denom; while (cin) try cout << "Theirquotient:" << Quotient(numer, denom) << endl; catch (DivByZero) cout << "*** Denominatorcan'tbe 0" << endl; cout << "Enternumeratorand denominator:"; cin >> numer >> denom; return 0; int Quotient(/*in */intnumer, // The numerator /*in */intdenom) // The denominator if(denom == 0) throw DivByZero(); return numer / deno m; 56/134 (c) pk 3

57 Functions in C++ Functions For : COP Object oriented Programming (Using C++) Declarations vs Definitions Inline Functions Class Member functions Overloaded Functions Pointers to functions Recursive functions Piyush Kumar Function body is a scope What you should know? Defining a function // return the greatest common divisor int gcd(int v1, int v2) while (v2) int temp = v2; v2 = v1 % v2; v1 = temp; return v1; Non-reference parameter. Gcd Example 1071, , 42 42, 21 21, 0 Another scope. temp is a local variable function gcd(a, b) if b = 0 return a else return gcd(b, a mod b) Calling a function? #include <iostream> using std::cout; using std::endl; using std::cin; int main() // get values from standard input cout << "Enter two values: \n"; int i, j; cin >> i >> j; // call gcd on arguments i and j // and print their greatest common divisor cout << "gcd: " << gcd(i, j) << endl; return 0; Function return types Parameter Type-Checking // missing return type Test(double v1, double v2) /* */ int *foo_bar(void) /* */ void process ( void ) /* */ int manip(int v1, v2) /* */ // error gcd( hello, world ); gcd(24312); gcd(42,10,0); gcd(3.14, 6.29); // ok? // Statically typed language int manip(int v1, int v2) /* */ // ok 57/134 (c) pk 1

58 Pointer Parameters Const parameters #include <iostream> #include <vector> using std::vector; using std::endl; using std::cout; void reset(int *ip) *ip = 0; // changes the value of the object to which ip points ip = 0; // changes only the local value of ip; the argument is unchanged Fcn(const int i) Fcn can read but not write to i. int main() int i = 42; int *p = &i; cout << "i: " << *p << '\n'; // prints i: 42 reset(p); // changes *p but not p cout << "i: " << *p << endl; // ok: prints i: 0 return 0; Reference Parameters // vec is potentially large, so copying vec might be expensive // use a const reference to avoid the copy void print(const vector<int> &vec) for (vector<int>::const_iterator it = vec.begin(); it!= vec.end(); ++it) if (it!= vec.begin()) cout << " "; cout << *it; cout << endl; Can be used to return information int main() vector<int> vec(42); print(vec.begin(), vec.end()); // Defined on next slide print(vec); Passing Iterators // pass iterators to the first and one past the last element to print void print(vector<int>::const_iterator beg, vector<int>::const_iterator end) while (beg!= end) cout << *beg++; if (beg!= end) cout << " "; // no space after last element cout << endl; Const references Passing reference to a pointer // When you don t what the function to modify the value associated with // the reference bool isshorter(const string &s1, const string &s2) return s1.size() < s2.size(); // swap values of two pointers to int void ptrswap(int *&v1, int *&v2) int *tmp = v2; v2 = v1; v1 = tmp; // v1 and v2 are the pointers passed to ptrswap themselves, // just renamed // The following link is out of the reach of this course: // Reading C/C++ declarations: 58/134 (c) pk 2

59 Array parameters No return values? void printvalues(const int ia[10]); Parameter treated as const int * void swap (int &v1, int &v2); Returning from main Returning a reference #include <cstdlib> int main() bool some_failure = false; if (some_failure) return EXIT_FAILURE; else return EXIT_SUCCESS; #include <string> using std::string; #include <iostream> using std::cout; using std::endl; //inline version: find longer of two strings inline const string & shorterstring(const string &s1, const string &s2) return s1.size() < s2.size()? s1 : s2; int main() string s1("successes"), s2("failure"); cout << shorterstring(s1, s2) << endl; Tip 1: Never return a reference to a local object. Tip 2: Never return a pointer to a local object. Put these in header files. return 0; Recursion Recursion Recursion is the process a procedure goes through when one of the steps of the procedure involves rerunning the entire same procedure. function factorial(n) if (n <= 1) return 1; else return n * factorial(n-1); Fibonacci number sequence: F(n) = F(n 1) + F(n 2). 59/134 (c) pk 3

60 Recursion Recursion template <typename T> void recsort(t begin, T end) int len = distance(begin,end); if( len <= 1) return; for(int i = 1; i < len; ++i) if(*(begin+i) < *(begin)) swap( *(begin+i), *(begin) ); recsort(begin+1,end); int main() vector<int> vs; int N = 10; for(int i = 0; i < N; ++i) vs.push_back(rand()); recsort(vs.begin(), vs.end()); for(int i = 0; i < N; ++i) cout << vs[i] << endl; return 0; Recursion Recursion template <typename T> void recsort(t begin, T end) int len = distance(begin,end); if( len <= 1) return; for(int i = 1; i < len; ++i) if(*(begin+i) < *(begin)) swap( *(begin+i), *(begin) ); recsort(begin+1,end); Generates void recsort(vector<int>::iterator begin, vector<int>::iterator end) int len = distance(begin,end); if( len <= 1) return; for(int i = 1; i < len; ++i) if(*(begin+i) < *(begin)) swap( *(begin+i), *(begin) ); recsort(begin+1,end); Can you see the recursion in a Sudoku solver? Another example. void printnum(int n) if (n >= 10) printnum(n/10); print(n%10); Another version. void printnumb(int n, int b) if (n >= b) printnumb(n/b); print(n%b); Recursion Recursion Eight Queens problem: Brute force solution: 64^8 = 2^48 = 281,474,976,710,656 possible blind placements of eight queens, The eight queens puzzle is based on the problem of putting eight chess queens on an 8 8 chessboard such that none of them is able to capture any other using the standard chess queen's moves. Invariants: no two pieces can share the same row any solution for n queens on an n m board must contain a solution for n 1 queens on an (n 1) m board proceeding in this way will always keep the queens in order, and generate each solution only once. 60/134 (c) pk 4

61 Backtracking A strategy for guessing at a solution and backing up when an impasse is reached Recursion and Backtracking can be used together to solve our problem (and many other problems) Eight Queens An observation that eliminates many arrangements from consideration No queen can reside in a row or a column that contains another queen Now: only 40,320 (8!) arrangements of queens to be checked for attacks along diagonals Eight Queens The Eight Queens Problem A recursive algorithm that places a queen in a column Base case If there are no more columns to consider You are finished Recursive step If you successfully place a queen in the current column Consider the next column If you cannot place a queen in the current column You need to backtrack Figure 5.1 a) Five queens that cannot attack each other, but that can attack all of column 6; b) backtracking to column 5 to try another square for the queen; c) backtracking to column 4 to try another square for the queen and then considering column 5 again Default Arguments Static variables. int ff(int i = 0); screen = screeninit( string::size_type height = 24, string::size_type width = 80, char background = ); string screen = screeninit(); string screen = screeninit(66); string screen = screeninit(66,256); string screen = screeninit(66,256, # ); string screen = screeninit(,,? ); // error string screen = screeninit(? ); // calls (?,80, ); Retain their values across function calls. In this course you are barred from using them. You can also call functions to initialize default Arguments. These functions are called when the function is called. 61/134 (c) pk 5

62 Function overloading Functions having same name but different parameter types. Record lookup(const Account&); Record lookup(const Phone&); Record lookup(const Name&); Record lookup(const SS&); 62/134 (c) pk 6

63 Classes: Methods, Constructors, Destructors and Assignment For : COP Object oriented Programming (Using C++) Piyush Kumar Classes: Member functions // classes example #include <iostream> using namespace std; class Square int x; int area () return (x*x);; void set_values(int a); int get_sidelen(void) const; ; void Square::set_values(int a) x = a; ; int Square::get_sidelen(void) const return x; int main () Square s; s.set_values (3); cout << "area: " << s.area(); return 0; Member functions: Methods Objects : Reminder private members of a class are accessible only from within other members of the same class or from their friends. protected members are accessible from members of their same class and from their friends, but also from members of their derived classes. Finally, public members are accessible from anywhere where the object is visible. An object is an instance of a class. Memory is allocated for each object instantiated (and not for the class). Example: Square S; // S is an object of Square class. (on stack) Square *ps = new Square; // on heap. An object of a class can be defined in the same way as an internal type. Objects : Reminder Objects: Reminder Multiple objects of a class can be created (as many as you want). All the objects share the same copy of member functions. But, they maintain a separate copy of data members. The data members and member functions of an object have the same properties as the data members and member functions of its class. Square s1,s2; // each has separate copy of x 63/134 (c) pk 1

64 Assignment operator Variable assignment Square s3 = s2; By default, copying a class object is equivalent to copying all its elements including pointers. Values are assigned to variables and not to their data types. Hence, you assign values to members of an object and not a class. Must create a unique object of a class because you cannot assign values to a class. Square = 5 is meaningless Back to member functions Member functions The member functions in the public section of a class can be accessed using the. operator for instantiated objects. (For pointers its -> ) Square s1, *s2; s1.set_values(5); s2 = new Square; s2->set_values(10); delete s2; Only the public members of an object can be directly accessed. Special Member functions Constructors & Destructors Constructors: Are invoked to initialize the data members of a class. Can not return any value (not even void). Can accept any parameters as needed. What would happen if we called the member function area() before having called function set_values()? Constructors initialize the objects in your class. Destructors cleans up and frees memory you may have allocated when the object was created. 64/134 (c) pk 2

65 Constructors Constructors Differs from other member functions. Initializes a newly created object. Other member functions are invoked by existing objects. A Constructor is invoked automatically when an object is created. // classes example #include <iostream> using namespace std; Have the same name as the class. class Square int x; Square(int w) x = w; ; int area () return (x*x);; void set_values(int a); int get_sidelen(void) const; ; void Square::set_values(int a) x = a; ; int Square::get_sidelen(void) const return x; int main () Square s(3); cout << "area: " << s.area(); return 0; Constructors Constructors: Overloading Have the same name as the class. class Square int x; Square() x = 0; ; int area () return (x*x);; void set_values(int a); int get_sidelen(void) const; ; void Square::set_values(int a) x = a; ; int Square::get_sidelen(void) const return x; int main () Square s; cout << "area: " << s.area(); return 0; You can have several constructors for a class by overloading them. class Square int x; Square(int w) x = w; ; Square() x = 0; ; int area () return (x*x);; void set_values(int a); int get_sidelen(void) const; ; Default constructor is defined for you: Square(); Constructors : Initialization Constructors: Warning Prefer initialization to assignment Square(int w):x(w); Array(int lowbound, int highbound):size(highboundlowbound+1), lb ( lowbound ), hb (highbound), data_vector(size) ; // Problematic? Why? List members in an initialization list in the order they were declared. If you implement no constructor, the compiler automatically generates a default constructor for you But if you write any constructors at all, the compiler does not supply a default constructor. 65/134 (c) pk 3

66 Copy Constructors Copy constructors: When is it called? Gets called in a number of situations. If you do not write one, the compiler automatically generates one for you. When the return value of a function has class type. Fraction process_fraction (int i, int j); When an argument has class type. A copy of the argument is made and passed to the function int numerator_process (Fraction f); When you use one object to initialize another object. Fraction a(1,3); Fraction b(a); Copy constructors Copy constructors Not passed when a pointer to an object is passed. It s only called when a new copy of an existing object needs to be created. The syntax: class_name(class_name const &source) Const: Making a copy should not alter source. &: The function should not need to call another copy constructor! Copy Constructors: Example. class Point int x,y; int xx(void) const return x;; int yy(void) const return y;; Point(Point const &p) this->x = p.xx(); this->y = p.yy(); ; ; Destructors You can have many constructors but only one destructor. The destructor must have the same name as the class, but preceded with a tilde sign (~) and it must also return no value. The use of destructors is especially suitable when an object assigns dynamic memory during its lifetime and at the moment of being destroyed we want to release the memory that the object was allocated. 66/134 (c) pk 4

67 // example on constructors and destructors (from cplusplus.com) #include <iostream> using namespace std; class CRectangle int *width, *height; CRectangle (int,int); ~CRectangle (); int area () return (*width * (*height)); ; Pointers to functions Not in syllabus. CRectangle::CRectangle (int a, int b) width = new int; height = new int; *width = a; *height = b; CRectangle::~CRectangle () delete width; delete height; int main () CRectangle rect (3,4), rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; this pointer Back to destructor example Useful when a member function manipulates two or more objects. It holds the address of the object for which the member function is invoked. It is always passed to a non-static member function. This ensures the right object is updated using member functions. What will happen if we do: CRectangle r1(10,20),r2(30,40); r1 = r2; The default assignment operator generated by the compiler is called. What is wrong with that in this example? // example on constructors and destructors (from cplusplus.com) #include <iostream> using namespace std; class CRectangle int *width, *height; CRectangle (int,int); ~CRectangle (); int area () return (*width * (*height)); ; CRectangle::CRectangle (int a, int b) width = new int; height = new int; *width = a; *height = b; CRectangle::~CRectangle () delete width; delete height; int main () CRectangle rect (3,4), rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; Assignment operators int x; x = 4; 4 = x? // non-lvalue in assignment x = y = z = 8; Z is assigned 8 first Y is then assigned the value of returned by (z = 8) which is 8. x is now assigned the value returned by (y = 8) which is 8 67/134 (c) pk 5

68 Assignment operators Assignment operators Complex x, y, z; x = (y = z); Writing this in equivalent functional form: x.operator=(y.operator=(z)); Square s1 = s2; The default behavior : Performs simple member by member copy. (This is the one generated by the compiler) Is the assignment operator the same thing as copy constructor? Assignment Operator Assignment Operator Copy constructor initializes an object. Assignment operator copies values to an existing object. Hence, in some cases: Copy constructor has to do more work than assignment operator. The syntax: class_name& operator=(const class_name &source) Const: Making an assignment should not alter source. &: The function should not need to call a copy constructors. An Example #include <iostream> #include <string.h> using namespace std; class Buf Buf( char* szbuffer, size_t sizeofbuffer ); Buf& operator=( const Buf & ); void Display() cout << buffer << endl; private: char* buffer; size_t SizeOfBuffer; ; Buf::Buf( char* szbuffer, size_t sizeofbuffer ) sizeofbuffer++; // account for a NULL terminator buffer = new char[ sizeofbuffer ]; if (buffer) memcpy( buffer, szbuffer, sizeofbuffer ); SizeOfBuffer = sizeofbuffer; Buf& Buf::operator=( const Buf &otherbuf ) if( &otherbuf!= this ) if (buffer) delete [] buffer; SizeOfBuffer = strlen( otherbuf.buffer ) + 1; buffer = new char[sizeofbuffer]; memcpy( buffer, otherbuf.buffer, SizeOfBuffer ); return *this; 68/134 (c) pk 6

69 Guidelines int main() Buf mybuf( "my buffer", 10 ); Buf yourbuf( "your buffer", 12 ); // Display 'my buffer' mybuf.display(); // assignment opperator mybuf = yourbuf; // Display 'your buffer' mybuf.display(); Place the common code used by the assignment operator and the copy constructor in a separate function and have each one call the function. This will make your code more compact and avoid duplication. A String class must copy a character string during the copy constructor and during an assignment. If we place this common code into a private member function void CopyString(const char* ptr); then both the copy constructor and assignment operator may call this routine to perform the copy rather than duplicate this code in each. From: Guidelines Guidelines If your class has pointer data, you must provide an assignment operator. If writing an assignment operator, you must also write a copy constructor. The generated assignment operator performs member-wise assignment on any data members of your class. For pointer variables, we almost always do not want this because the data members of the copy will point to the same data as the copied object! Worse, if one of the objects is destroyed, the data is destroyed with it. A run-time error will occur the next time the remaining object tries to access the now nonexistent data. Always implement the assignment operator for your class; do not let the compiler generate the default assignment operator. The compiler will generate a default assignment operator for your class if you do not provide one. In order to be in complete control of how your class operates, always provide an assignment operator. Guidelines Guidelines Check for assignment to self. Disaster can result if a variable is assigned to itself. Consider: X x; x = x; Suppose class X contains pointer data members that are dynamically allocated whenever an object is created. Assignment always modifies an existing object. The dynamic data will, therefore, be released before assigning the new value. If we do not check for assignment to self, the above assignment will delete the existing pointer data, and then try to copy the data that was previously deleted! The destructor must release any resources obtained by an object during its lifetime, not just those that were obtained during construction. Make the constructor as compact as possible to reduce overhead and to minimize errors during construction. 69/134 (c) pk 7

70 Classes II: Type Conversion, Friends, For : COP Object oriented Programming (Using C++) Abstraction and Encapsulation Abstraction: Separation of interface from implementation Encapsulation: Combining lower level elements to form higher-level entity. Access Labels (public/private/protected) enforce abstraction and encapsulation. Piyush Kumar Concrete Types. A concrete class is a class that exposes, rather than hides, its implementation Example : pair<> (defined in <utility>) Exists to bundle two data members. Example: Benefits of Abstraction & Encapsulation Class internals are protected from user-lever errors. Class implementation may evolve over time without requiring change in user-level code. //-- Declare a pair variable. pair<string, int> pr1; //-- Declare and initialize with constructor. pair<string, int> pr2("heaven", 7); cout << pr2.first << "=" << pr2.second << endl; // Prints heaven=7 More on Class definitions Using Typedefs to streamline classes. class Screen private: std::string contents; std::string::size_type cursor; std::string::size_type height,width; class Screen typedef std::string::size_type index; private: std::string contents; index cursor; index height,width; inline Screen::index Screen::get_cursor() const return cursor; 70/134 (c) pk 1

71 Class declaration class Screen; // declaration of the class Forward declaration: Introduces the name Screen into the program and indicates that Screen refers to a class name. Incomplete Type: After declaration, before definition, Screen is an incomplete type. It s known screen is a type but not known what members that type contains. Class declaration for class members. Because a class is not defined until its class body is complete, a class cannot have data members of its own type. A class can have data members that are pointers or references to its own type. class Human Screen window; Human *bestfriend; Human *father, *mother; Using this pointer Using this pointer How do we implement the Screen class so that the following is allowed: myscreen.move(4,0).set( # ) Equivalent to: myscreen.set(4,0); myscreen.set( # ) Return reference to Screen in the member functions. Screen& move(index r, index c); Screen& set(char); Implementation: Screen& Screen::move(index r,index c) index row = r* width; cursor = row +c; return *this; Using this pointer Mutable data members Beware of const: const Screen& Screen::display(ostream &os) const os << contents; return *this; myscreen.move(4,0).set( # ).display(cout) Sometimes, you might want to modify a variable inside a const member function. A mutable data member is a member that is never const (even when it is a member of a const object). 71/134 (c) pk 2

72 Mutable data members Guideline. class Screen private: mutable size_t access_ctr; ; void Screen::do_display(std::ostream& os) const ++access_ctr; // keep count of calls to any member func. os << contents; Never repeat code. If you have member functions that need to have repeated code, abstract it out in another function and make them call it (maybe inline it). Type conversion: Revisited Type conversions: revisited int i; float f; f = i; // implicit conversion f = (float)i; // explicit conversion f = float(i); // explicit conversion Can convert from one type into this type with constructor Bitset( const unsigned long x ); How do we convert from this type to something else? Create an operator to output the other type Later. Implicit Type conversion Beware: A constructor that can be called with a single argument defines an implicit conversion from the parameter type to the class type. Class Sales_item Public: Sales_item(const std::string &book = ) : isbn (book), units_sold(0), revenue(0.0) class String String( int length ); // Allocation constructor //... ; // Function that receives an object of type String as an argument void foo( const String& astring ); // Here we call this function with an int as argument int x = 100; foo( x ); // Implicit conversion: foo( String( x ) ); String null_book = ; Item.sale_isbn(null_book); // implicit type conversion.. 72/134 (c) pk 3

73 Use of implicit type conversion class String String( char* cp ); // Constructor operator const char* () const; // Conversion operator to const char* //... ; Suppressing implicit conversions. Use explicit before conversion constructors. explicit String( char* cp ); // Constructor void foo( const String& astring ); void bar( const char* somechars ); // main.cc int main() foo( "hello" ); // Implicit type conversion char* -> String String peter = "pan"; bar( peter ); // Implicit type conversion String -> const char* Friends. friend function/classes Can access private and protected (more later) members of another class friend functions are not member functions of class Defined outside of class scope A Friend declaration begins with the keyword friend Friends Properties Friendship is granted, not taken NOT symmetric if B a friend of A, A not necessarily a friend of B NOT transitive if A a friend of B, B a friend of C, A not necessarily a friend of C. Friends friend declarations friend function Keyword friend before function prototype in class that is giving friendship. friend int myfunc( int x ); Appears in the class granting friendship friend class Type friend class Classname in class granting friendship If ClassOne granting friendship to ClassTwo, friend class ClassTwo; appears in ClassOne's definition Friends Why use friends? to provide more efficient access to data members than the function call to accommodate operator functions with easy access to private data members Be careful: Friends can have access to everything, which defeats data hiding. Friends have permission to change the internal state from outside the class. Always use member functions instead of friends to change state 73/134 (c) pk 4

74 An example #include <iostream> #include <string> class Sales_item friend bool operator==(const Sales_item&, const Sales_item&); friend std::istream& operator>>(std::istream&, Sales_item&); friend std::ostream& operator<<(std::ostream&, const Sales_item&); // other members as before // added constructors to initialize from a string or an istream Sales_item(const std::string &book): isbn(book), units_sold(0), revenue(0.0) Sales_item(std::istream &is) is >> *this; // operations on Sales_item objects // member binary operator: left-hand operand bound to implicit this pointer Sales_item& operator+=(const Sales_item&); // other members as before 74/134 (c) pk 5

75 Introduction to Data Structures For : COP Object oriented Programming (Using C++) Piyush Kumar Sorted Arrays As Lists Arrays are used to store a list of values Arrays are contained in contiguous memory Recall inserting a new element in the middle of an array requires later elements to be "shifted". For large lists of values, this is inefficient. void insertsorted(int value, int &length, int list[]) int i = length - 1; Shifting array elements while (list[i] > value) that come after the element being inserted list[i + 1] = list[i]; i--; list[i + 1] = value; length++; 4 8 Insert Sorted Arrays Due to the need to "shift" elements, sorted arrays are: Inefficient when inserting into the middle or front Inefficient when deleting from the middle or front Efficient for searching Since inserting and deleting are common operations, we need to find a data structure which allows more efficiency Contiguous memory will not work will always require a shift "Random" placement requires "random" memory locations Dynamic allocation provides "random" locations, and means that the list can grow as much as necessary The maximum size need not be known ever This is not true for arrays, even dynamically allocated arrays Intro To Linked Lists A linked list is a data structure which allows efficient insertion and deletion. Consists of "nodes". Each node contains: A value - the data being stored in the list A pointer to another (the next) node By carefully keeping pointers accurate, you can start at the first node, and follow pointers through entire list. Graphically, linked list nodes are represented as follows: value ptr Linked List Info Each node is dynamically allocated, so memory placement is "random" "start" The above linked list may be stored in memory as shown to the right "start" C C C *0 2 *1030 * *1004 Deletion From Linked Lists Given the initial linked list: Delete node with value Resulting in /134 (c) pk 1

76 Insertion Into Linked Lists Given the initial linked list: Insert node with value 5 Resulting in Linked List Nodes, Example Use a class to group the value and the pointer class ListNodeClass // Only for illustration: Bad design int val; //Will have a list of ints ListNodeClass *next; //Point to the next node ; int main() ListNodeClass *head = 0; //Essentially, this declares a //list, since it will point to the //first node of a list. Initially, //list is empty (null pointer) head = new ListNodeClass; //Note no [] - not //declaring an array - just //one single node... Printing a List (Visiting Each Node) void printlist(listnodeclass *head) ListNodeClass *temp = head; if (temp == 0) cout << "List is Empty!" << endl; else while (temp!= 0) cout << temp->val << " "; temp = temp->next; cout << endl; Try To Insert To Front Of List bool insertathead1(listnodeclass *head, int newval) bool status = true; ListNodeClass *temp; temp = new ListNodeClass; if (temp == 0) cout << "Unable to alloc node" << endl; status = false; else temp->val = newval; if (head == 0) temp->next = 0; head = temp; else temp->next = head; head = temp; return (status); int main(void) ListNodeClass *head1 = 0; printlist(head1); insertathead1(head1, 5); insertathead1(head1, 8); insertathead1(head1, 17); printlist(head1); return (0); List is Empty! List is Empty! Corrected Insert To Front Of List bool insertathead(listnodeclass **head, int newval) bool status = true; ListNodeClass *temp; temp = new ListNodeClass; if (temp == 0) cout << "Unable to alloc node" << endl; status = false; else temp->val = newval; if (*head == 0) temp->next = 0; *head = temp; else temp->next = *head; *head = temp; return (status); int main(void) ListNodeClass *head = 0; printlist(head); insertathead(&head, 5); insertathead(&head, 8); insertathead(&head, 17); printlist(head); return (0); List is Empty! Reference to pointer example // Reference to pointer example #include <iostream> using namespace std; void increment(int*& i) i++; int main() int* i = 0; cout << "i = " << i << endl; increment(i); cout << "i = " << i << endl; /134 (c) pk 2

77 Deleting From Front Of List bool deletefromfront( ListNodeClass **head) bool status = true; ListNodeClass *temp; if (*head == 0) cout << "Can't delete from list" << endl; status = false; else temp = *head; *head = temp->next; //Free the memory we dynamically //allocated in insert function delete temp; return (status); int main(void) ListNodeClass *head = 0; printlist(head); insertathead(&head, 5); insertathead(&head, 8); insertathead(&head, 17); printlist(head); deletefromfront(&head); printlist(head); deletefromfront(&head); deletefromfront(&head); printlist(head); deletefromfront(&head); return (0); List is Empty! List is Empty! Cannot delete from list! Searching A List bool searchlist(listnodeclass *head, int val) bool found = false; ListNodeClass *temp = head; while (temp!= 0 &&!found) if (temp->val == val) found = true; else temp = temp->next; return (found); The Stack Linked Structure A stack is another data structure Used to organize data in a certain way Think of a stack as a stack of cafeteria trays Take a tray off the top of the stack Put washed trays on the top of the stack taketray() puttray() Bottom tray is not accessed unless it is the only tray in the stack. Since only the top of a stack can be accessed, there needs to be only one insert function and one delete function Inserting to a stack is usually called "push" Deleting from a stack is usually called "pop" The Queue Linked Structure A queue is another data structure. Think of a queue as a line of people at a store Get into the line at the back (insert) Person at front is served next (delete) Get In Line Serve Customer Server Can only insert at one end of the queue. Inserting to a queue is usually called "enqueue()" "Get In Line" in above diagram Can only remove at the other end of the queue Removing from a queue is usually called "dequeue()" "Serve Customer" in above diagram Another Queue Pic: FIFO Priority Queue Pic: FIFO First In First out. Mark Nelson Highest priority goes out first. The STL has three container adaptor types: stack, queue, and priority_queue. Mark Nelson 77/134 (c) pk 3

78 The Priority Queue Linked Structure A priority queue works slightly differently than a "normal" queue Elements in a priority queue are sorted based on a priority Queue order is not dependent on the order in which elements were inserted, as it was for a normal queue As elements are inserted, they are sorted such that the element with the highest priority is at the beginning of the priority queue When an element is removed from the priority queue, the first element (highest priority) is taken, regardless of when it was inserted Elements of the same priority are maintained in the order which they were inserted Using a priority queue in which all elements have the same priority is equivalent to using a "normal" queue The Doubly-Linked List Structure The linked list examples we've seen so far have only one pointer Often, it may be advantageous to have a node contain multiple "head" pointers "tail" class DoublyLinkedListNodeClass DoublyLinkedListNodeClass *prev; int val; DoublyLinkedListNodeClass *next; ; DoublyLinkedListNodeClass *head; DoublyLinkedListNodeClass *tail; STL list<> A list is a doubly linked list. Example list<int> L; L.push_back(0); L.push_front(1); L.insert(++L.begin(), 2); copy(l.begin(), L.end(), ostream_iterator<int>(cout, " ")); // The values that are printed are Container Adaptors Container adaptors take sequence containers as their type arguments, for example: stack < vector < int > > a; Note that singly linked lists, which only support forward traversal, are also sometimes useful. If you do not need backward traversal, then slist may be more efficient than list. Stack (Last In First Out) Use with vector (best/default), deque, or list (bad choice) Basic interface: bool empty(); size_type size(); value_type& top(); const value_type& top(); void push(const value_type&); void pop(); Stack #include <stack> Container Function back() push_back() pop_back() empty() size() Provides: stack<t, Sequence> Stack Adapter Function top() push() pop() empty() size() To support this functionality stack expects the underlying container to support push_back(), pop_back(), empty() or size() and back() 78/134 (c) pk 4

79 Stack Example. // C++ STL Headers #include <iostream> #include <vector> #include <stack> int main( int argc, char *argv[] ) stack<const char *, vector<const char *> > s; // Push on stack in reverse order s.push("order"); s.push("correct"); // Oh no it isn't! s.push("the"); s.push("in"); s.push("is"); s.push("this"); // Pop off stack which reverses the push() order while (!s.empty() ) cout << s.top() <<" "; s.pop(); /// Oh yes it is! cout << endl; return( EXIT_SUCCESS ); Phil Ottewell's STL Tutorial Simpler Stack example int main() stack<int> S; S.push(8); S.push(7); S.push(4); assert(s.size() == 3); assert(s.top() == 4); S.pop(); assert(s.top() == 7); S.pop(); assert(s.top() == 8); S.pop(); assert(s.empty()); Queue #include <queue> #include <vector> #include <list> #include <iostream> int main( ) using namespace std; Use with deque (default), or list. (Vector works, but its extremely inefficient) Basic interface: bool empty(); size_type size(); value_type& front(); const value_type& front(); value_type& back(); const value_type& back(); void push(const value_type&); void pop(); // Declares queue with default deque base container queue <char> q1; // Explicitly declares a queue with deque base container queue <char, deque<char> > q2; // These lines don't cause an error, even though they // declares a queue with a vector base container queue <int, vector<int> > q3; q3.push( 10 ); // but the following would cause an error because vector has // no pop_front member function // q3.pop( ); // Declares a queue with list base container queue <int, list<int> > q4; // The second member function copies elements from a container list<int> li1; li1.push_back( 1 ); li1.push_back( 2 ); queue <int, list<int> > q5( li1 ); cout << "The element at the front of queue q5 is " << q5.front( ) << "." << endl; cout << "The element at the back of queue q5 is " << q5.back( ) << "." << endl; int main() priority_queue<int> Q; Q.push(1); Q.push(4); Q.push(2); Q.push(8); Q.push(5); Q.push(7); assert(q.size() == 6); assert(q.top() == 8); Q.pop(); Graphs assert(q.top() == 7); Q.pop(); assert(q.top() == 5); Q.pop(); assert(q.top() == 4); Q.pop(); An introduction assert(q.top() == 2); Q.pop(); assert(q.top() == 1); Q.pop(); assert(q.empty()); 79/134 (c) pk 5

80 Graphs Directed graph A graph G = (V,E) is composed of: V: set of vertices E V V: set of edges connecting the vertices An edge e = (u,v) is a pair of vertices Directed graphs (ordered pairs) Undirected graphs (unordered pairs) Directed Graph Undirected GRAPH Undirected Graph Some More Graph Applications Graph transportation Nodes street intersections highways Edges communication computers fiber optic cables World Wide Web web pages hyperlinks social people relationships food web species predator-prey software systems functions function calls scheduling tasks precedence constraints circuits gates wires 80/134 (c) pk 6

81 World Wide Web 9-11 Terrorist Network Web graph. Social network graph. Node: people. Node: web page. Edge: hyperlink from one page to another. Edge: relationship between two people. cnn.com netscape.com novell.com cnnsi.com timewarner.com hbo.com sorpranos.com Reference: Valdis Krebs, Ecological Food Web Terminology Food web graph. Node = species. Edge = from prey to predator. a is adjacent to b iff (a,b) Ε. degree(a) = number of adjacent vertices (Self loop counted twice) Self Loop: (a,a) a Parallel edges: E =...(a,b), (a,b)... Reference: a b Terminology Question A Simple Graph is a graph with no self loops or parallel edges. Incidence: v is incident to e if v is an end vertex of e. Max Degree node? Min Degree Node? Isolated Nodes? Total sum of degrees over all vertices? Number of edges? v e 81/134 (c) pk 7

82 QUESTION Connected graph How many edges are there in a graph with 100 vertices each of degree 4? Undirected Graphs: If there is at least one path between every pair of vertices. (otherwise disconnected) complete graph Trees Every pair of graph vertices is connected by an edge. An undirected graph is a tree if it is connected and does not contain a cycle. Theorem. Let G be an undirected graph on n nodes. Any two of the following statements imply the third. G is connected. G does not contain a cycle. G has n-1 edges. n(n-1)/2 edges representation Two ways Adjacency List ( as a linked list for each node in the graph to represent the edges) Adjacency Matrix (as a boolean matrix) Representing Graphs Vertex 1 2 Adjacent Vertices 2, 3, 4 1, 4 4 Initial Vertex Terminal Vertices , , 2, 3 4 1, 2, 3 82/134 (c) pk 8

83 adjacency list adjacency matrix Another example AL Vs AM AL : Total space = 4 V + 8 E bytes (For undirected graphs its 4 V + 16 E bytes) AM : V * V / 8 Question: What is better for very sparse graphs? (Few number of edges) AL Vs AM Question: How much time does it take to find out if (v i,v j ) belongs to E? AM? AL? Stable Marriage Our next problem 83/134 (c) pk 9

84 The problem Other Similar problems There are n men and n women Each man has a preference list, so does the woman. These lists have no ties. Devise a system by which each of the n men and n women can end up getting married. Given a set of colleges and students pair them. (Internship Company assignments) Given airlines and pilots, pair them. Given two images, pair the points belonging to the same point in 3D to extract depth from the two images. Dorm room assignments. Hospital residency assignments**. Your first programming assignment Stereo Matching Example Preference Lists Man 1 st 2 nd 3 rd Woman 1 st 2 nd 3 rd X A B C A Y X Z Y B A C B X Y Z Z A B C C X Y Z What goes wrong? Fact: If one knows the distance between the cameras And the matching, its almost trivial to recover depth.. Unstable pairs: (X,C) and (B,Y) They prefer each other to current pairs. Stable Matching Another Stable Matching Man 1 st 2 nd 3 rd Woman 1 st 2 nd 3 rd Man 1 st 2 nd 3 rd Woman 1 st 2 nd 3 rd X A B C A Y X Z X A B C A Y X Z Y B A C B X Y Z Y B A C B X Y Z Z A B C C X Y Z Z A B C C X Y Z No Pairs creating instability. 84/134 (c) pk 10

85 Stability is Primary. Main Idea Any reasonable list of criteria must contain the stability criterion. A pairing is doomed if it contains a shaky couple. Idea: Allow the pairs to keep breaking up and reforming until they become stable Can you argue that the couples will not continue breaking up and reforming forever? Men Propose (Women dispose) Initialize each person to be free. while (some man m is free and hasn't proposed to every woman) w = first woman on m's list to whom m has not yet proposed if (w is free) assign m and w to be engaged else if (w prefers m to her fiancé m') assign m and w to be engaged, and m' to be free else w rejects m Gale-Shapley Algorithm (men propose) 85/134 (c) pk 11

86 Operator Overloading For : COP Object oriented Programming (Using C++) Operator overloading C++ allows overloading of most of the standard operators. We are allowed to define standard operators for new types. The name of an operator, as a function, is operator followed by the operator itself. The operator in a - b is named operator-. Suppose we have a class MyNum, a new numerical type. The syntax for defining operators is ReturnType operator@(argument list ) For example: MyNum operator-(const MyNum & a, const MyNum &b); Piyush Kumar Example class MyNum... ; Example class MyNum... ; // Without operator overloading: MyNum add(const MyNum& x, const MyNum& y); MyNum mul(const MyNum& x, const MyNum& y); MyNum f(const MyNum& a, const MyNum& b, const MyNum& c) return add(add(mul(a,b), mul(b,c)), mul(c,a)); // Yuk... // With operator overloading: MyNum operator+ (const MyNum& x, const MyNum& y); MyNum operator* (const MyNum& x, const MyNum& y); MyNum f(const MyNum& a, const MyNum& b, const MyNum& c) return a*b + b*c + c*a; C++ FAQ C++ FAQ More examples? Operator Overloading Here are a few of the many examples of operator overloading: mystring + yourstring might concatenate two std::string objects mydate++ might increment a Date object a * b might multiply two Number objects a[i] might access an element of an Array object x = *p might dereference a "smart pointer" that "points" to a disk record it could seek to the location on disk where p "points" and return the appropriate record into x Operator overloading makes life easier for the users of a class, not for the developer of the class! Supports more natural usage. Uniformity with built in types. 86/134 (c) pk 1

87 Operator Overloading: Another example Precedence of Operators class Array int& elem(unsigned i) if (i > 99) error(); return data[i]; private: int data[100]; ; int main() Array a; a.elem(10) = 42; a.elem(12) += a.elem(13);... class Array int& operator[] (unsigned i) if (i > 99) error(); return data[i]; private: int data[100]; ; int main() Array a; a[10] = 42; a[12] += a[13];... Ival = jval = kval = lval Right associative (Ival = (jval = (kval = lval))) Ival * jval / kval * lval Left associative (((Ival * jval) / kval) * lval) Operator Precedence in C++ Operator precedence :: -> global / class / namespace scopes. -> [] subscript () Parentheses Unary operators Multiplicative operators Additive operators Relational ordering Relational equality Logical and Logical or Assignment x == y + z; Precedence and associativity are fixed. We cannot create new operators. Nor can we change the precedence, associativity (grouping), or number of parameters. Overloading operators Operator Overloading The meaning of an operator for the built in types may not be changed. int operator+(int, int) // not allowed Operators that can not be overloaded ::,.*,.,?: Can I overload operator== so it lets me compare two char[] using a string comparison? No: at least one operand of any overloaded operator must be of some user-defined type (most of the time that means a class). And you shouldn t be using char[] anyways. 87/134 (c) pk 2

88 Operator Overloading Which ones should you override? The ones your user wants you to. Do not confuse your users. Use common sense. If your overloaded operator makes life easier and safer for your users, do it; otherwise don't Class member Vs non-member Operators can be global or member. As a member function, the first operand becomes its object, that is, *this. Substraction operator as a friend/global : MyNum operator-(const MyNum & a, const MyNum & b); As a member of class MyNum: class MyNum MyNum operator-(const MyNum & b) const; ; MyNum MyNum::operator-(const MyNum & b) const // Continue as usual Member Vs Non-Member Non-Member If MyNum::operator- defined as member function Num1 Num2 Num1.operator-(Num2) As a non-member function Num1 Num2 operator-(num1,num2) When operators are defined as nonmember functions, they often must be made friends. class Sales_item friend bool operator==(const Sales_item&, const Sales_item&); friend std::istream& operator>>(std::istream&, Sales_item&); friend std::ostream& operator<<(std::ostream&, const Sales_item&); // other members as before ostream& operator<<(ostream& out, const Sales_item& s) out << s.isbn << "\t" << s.units_sold << "\t" << s.revenue << "\t" << s.avg_price(); return out; Member Vs Non-Member Member Vs Non-Member =, [], (), -> must be defined as members ( else -> compile time error) Like assignment, compoundassignment operators ordinarily ought to be members. (but not required) Operators that change the state of the object such as increment, decrement and dereference -- usually should be member functions. Symmetric operators like arithmetic, equality, relational, and bitwise operators, are best left as nonmembers. 88/134 (c) pk 3

89 Guideline: Guideline vector,deque,list,slist Not a good idea to overload,, &, &&, These operators have built in meanings that become inaccessible if we define our own. An operation to test whether the object is empty could be represented by operator! (or in a good state ) A class that has +, = The provide += Classes that will be used as the key type of an associative container should define < An Associative Container is a variable-sized Container that supports efficient retrieval of elements (values) based on keys. It supports insertion and removal of elements, but differs from a Sequence in that it does not provide a mechanism for inserting an element at a specific position. [1] Associative Containers: set, multiset, hash_set, hash_multiset, map, multimap, hash_map, hash_multimap Types in containers Define == and < for types that will be stored in even sequential containers. Many algorithms (e.g. find()) assume that these operators exist Find() example list<mynum> nums; list<mynum>::iterator nums_iter; nums.push_back ( 3 ); nums.push_back ( 7 ); nums.push_front ( 10 ); nums_iter = find(nums.begin(), nums.end(), 3 ); // Search the list. if (nums_iter!= nums.end()) cout << "Number " << (*nums_iter) << " found." << endl; // 3 else cout << "Number not found." << endl; // If we found the element, erase it from the list. if (nums_iter!= nums.end()) nums.erase(nums_iter); // List now contains: 10 7 Equality and relational operators If you define == then also define!= If you define < then also define <=, >=, > Output Operator To be consistent with the IO library, the syntax of output operator is: ostream& operator<<(ostream& out, const Your_Class_Type& s) // any special logic to prepare object // actual output of members out << // // return ostream object return out; 89/134 (c) pk 4

90 Output Operators Generally, output operators print the contents of the object with minimal formatting. They should not print a newline. IO operators: Always Non-Member // if operator<< is a member of Sales_item Sales_item item; item << cout; The usage is the opposite of normal way we use output operators. Input operator overloading Arithmetic operators Must deal with end of file/errors. istream& operator>>(istream& in, Sales_item& s) double price; in >> s.isbn >> s.units_sold >> price; // check that the inputs succeeded if (in) s.revenue = s.units_sold * price; else s = Sales_item(); // input failed: reset object to default state return in; When designing an input operator, decide what to do about error handling. Sales_item& Sales_item::operator+=(const Sales_item& rhs) units_sold += rhs.units_sold; revenue += rhs.revenue; return *this; // assumes that both objects refer to the same isbn Sales_item operator+(const Sales_item& lhs, const Sales_item& rhs) Sales_item ret(lhs); // copy lhs into a local object that we'll return ret += rhs; // add in the contents of rhs return ret; // return ret by value Operator== inline bool operator==(const Sales_item &lhs, const Sales_item &rhs) return lhs.units_sold == rhs.units_sold && lhs.revenue == rhs.revenue && lhs.same_isbn(rhs); == means objects contain same data. Also define!= Classes which define == are easier to use with STL. (e.g. find()) Operator< and Sorting // // sort.cpp // #include <vector> #include <algorithm> #include <functional> #include <iostream> struct associate int num; char chr; associate(int n, char c) : num(n), chr(c); associate() : num(0), chr(' '); ; 90/134 (c) pk 5

91 Operator< and sorting bool operator<(const associate &x, const associate &y) return x.num < y.num; ostream& operator<<(ostream &s, const associate &x) return s << "<" << x.num << ";" << x.chr << ">"; Operator< and Sorting int main () vector<associate>::iterator i, j, k; associate arr[20] = associate(-4, ' '), associate(16, ' '), associate(17, ' '), associate(-3, 's'), associate(14, ' '), associate(-6, ' '), associate(-1, ' '), associate(-3, 't'), associate(23, ' '), associate(-3, 'a'), associate(-2, ' '), associate(-7, ' '), associate(-3, 'b'), associate(-8, ' '), associate(11, ' '), associate(-3, 'l'), associate(15, ' '), associate(-5, ' '), associate(-3, 'e'), associate(15, ' '); // Set up vectors vector<associate> v(arr, arr+20), v1((size_t)20), v2((size_t)20); // Copy original vector to vectors #1 and #2 copy(v.begin(), v.end(), v1.begin()); copy(v.begin(), v.end(), v2.begin()); // Sort vector #1 sort(v1.begin(), v1.end()); // Stable sort vector #2 stable_sort(v2.begin(), v2.end()); // Display the results cout << "Original sort stable_sort" << endl; for(i = v.begin(), j = v1.begin(), k = v2.begin(); i!= v.end(); i++, j++, k++) cout << *i << " " << *j << " " << *k << endl; return 0; Output : Original sort stable_sort <-4; > <-8; > <-8; > <16; > <-7; > <-7; > <17; > <-6; > <-6; > <-3;s> <-5; > <-5; > <14; > <-4; > <-4; > <-6; > <-3;e> <-3;s> <-1; > <-3;s> <-3;t> <-3;t> <-3;l> <-3;a> <23; > <-3;t> <-3;b> <-3;a> <-3;b> <-3;l> <-2; > <-3;a> <-3;e> <-7; > <-2; > <-2; > <-3;b> <-1; > <-1; > <-8; > <11; > <11; > <11; > <14; > <14; > <-3;l> <15; > <15; > <15; > <15; > <15; > <-5; > <16; > <16; > <-3;e> <17; > <17; > <15; > <23; > <23; > Subscript operator Must be a member-function Ordinarily, a class that defines subscript, defines two versions. A nonconst member returning a reference. A const member returning a const reference. Example Example #include <vector> using std::vector; #include <iostream> using std::cout; using std::endl; class Foo Foo(): data(100) for (int i = 0; i!= 100; ++i) data[i] = i; int &operator[](const size_t); const int &operator[](const size_t) const; // other interface members private: vector<int> data; // other member data and private utility functions ; int& Foo::operator[](const size_t index) return data[index]; // no range checking on index const int& Foo::operator[](const size_t index) const return data[index]; // no range checking on index int main() Foo f; cout << f[50] << endl; return 0; 91/134 (c) pk 6

92 Increment and Decrement operators // increment and decrement CheckedPtr operator++(int); CheckedPtr operator--(int); CheckedPtr& operator++(); CheckedPtr& operator--(); // postfix operators // prefix operators Increment and Decrement operator // postfix: increment/decrement object but return unchanged value CheckedPtr CheckedPtr::operator++(int) // no check needed here, the call to prefix increment will do the check CheckedPtr ret(*this); // save current value ++*this; // advance one element, checking the increment return ret; // return saved state // prefix: return reference to incremented/decremented object CheckedPtr& CheckedPtr::operator++() if (curr == end) throw out_of_range ("increment past the end of CheckedPtr"); ++curr; return *this; // advance current state ++ / -- Advice: Make them member functions. For consistency, Prefix operations should return a reference to the incremented/decremented object Postfix operations should return the old value (and not the reference) Calling prefix/postfix operators explicitly Mytype.operator++(0); // postfix Mytype.operator++(); // prefix Call operator and Function objects #include <iostream> using std::cout; using std::endl; struct absint int operator()(int val) return val < 0? -val : val; ; int main() int i = -42; absint absobj; // object that defines function call operator unsigned int ui = absobj(i); // calls absint::operator(int) cout << i << " " << ui << endl; return 0; Function call operator Must be a member function Can be overloaded for different parameters. Objects that have call operator overloaded are often referred to as Function Objects 92/134 (c) pk 7

93 Function Objects Template Function Objects A Function object, often called a functor or functionoid, is a computer programming construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax. An advantage of function objects in C++ is performance because unlike a function pointer, a function object can be inlined. class GenericNegate template <class T> T operator() (T t) const return -t; ; int main() GenericNegate negate; int64 val = i64; cout<< negate(5.3333); // double cout<< negate(val); // int64 Using count_if Using FOs with STL // determine whether a length of a given word is 6 or more bool GT6(const string &s) return s.size() >= 6; vector<string>::size_type wc = count_if(words.begin(), words.end(), GT6); class GT_cls GT_cls(size_t val =0) : bound(bal) bool operator() (const string &s) return s.size() >= bound; private: std::string::size_type bound; cout << count_if ( words.begin(), words.end(), GT_cls(6)) << words 6 characters or longer << endl; for(size_t I = 0; I!= 11; ++I) cout << count_if ( words.begin(), words.end(), GT_cls(i)) << words << I << characters or longer << endl; Using FOs with STL Using FOs with STL struct adder double sum; adder() : sum(0) ; void operator()(double x) sum += x; ; vector<int> V(100); generate(v.begin(), V.end(), rand); vector<double> V;... adder result = for_each(v.begin(), V.end(), adder()); cout << "The sum is " << result.sum << endl; 93/134 (c) pk 8

94 A slight deviation STL FOs // print.hpp #include <iostream> template <class T> inline void PRINT_ELEMENTS( const T& collection, const char * optcstr = ) typename T::const_iterator pos; std::cout << optcstr; for ( pos = collection.begin(); pos!= collection.end(); ++pos) std::cout << *pos << ; std::cout << std::endl; #include <functional> Types of function objects. Arithmetic FOs: plus<type>, minus<type>, multiplies<type>, divides<type>, modulus<type>, negate<type> Relational FOs: equal_to<type>, not_equal_to<type>, greater<type>, greater_equal<type>, less<type>, less_equal<type> Logical FOs: logical_and<type>, logical_or<type>, logical_not<type> Usage: PRINT_ELEMENTS(myvec, initialized to ); How do we do the same thing using function objects? STL FOs Another classification Unary FOs: negate<type>, logical_not<type> Binary FOs: The rest. Using library FOs with Algorithms sort(svec.begin(), svec.end(), greater<string>()); Sorts the container in ascending order. The third argument is used to pass a predicate function to use to compare elements. Function Adaptors and FOs Function Adaptors (FAs) FAs specialize and extend FOs. FA categories Binders: Converts a binary FO to a unary FO by binding one of the operands to a given value Negators: Reverses the truth value of a predicate function. Binder adaptors: bind1st, bind2nd bind1st binds the given value to the first argument of the binary function object. (bind2nd binds to the 2 nd ) count_if( vec.begin(), vec.end(), bind2nd( less_equal<int>(), 10)); 94/134 (c) pk 9

95 Function Adaptors Negators: not1 : Reverses the truth value of a unary predicate. not2 : Reverses the truth value of a binary predicate. Example: count_if( vec.begin(), vec.end(), not1(bind2nd( less_equal<int>(), 10))); Example (FAs n FOs) #include <functional> using std::plus; using std::negate; #include <iostream> using std::cout; using std::endl; #include <vector> #include <algorithm> using std::count_if; using std::bind2nd; using std::not1; using std::ptr_fun; using std::less_equal; using std::vector; #include <iostream> using std::cin; #include <string> using std::string; bool size_compare(string s, string::size_type sz) return s.size() >= sz; int main() cout << plus<int>()(3,4) << endl; // prints 7 plus<int> intadd; // function object that can add two int values negate<int> intnegate; // function object that can negate an int value // uses intadd::operator(int, int) to add 10 and 20 int sum = intadd(10, 20); // sum = 30 cout << sum << endl; int arry[] = 0,1,2,3,4,5,16,17,18,19; vector<int> vec(arry, arry + 10); cout << count_if(vec.begin(), vec.end(), bind2nd(less_equal<int>(), 10)); cout << endl; cout << count_if(vec.begin(), vec.end(), not1(bind2nd(less_equal<int>(), 10))); cout << endl; // uses intnegate::operator(int) to generate -10 as second parameter // to intadd::operator(int, int) sum = intadd(10, intnegate(10)); // sum = 0 cout << sum << endl; return 0; Predicate functions Returns bool. Should be a pure function: Only depend on its input parameters. F(x,y) should only depend on x,y. A predicate class is a FO whose operator() is a predicate. Example : less_equal<int> () Make FOs adaptable. list<widget *> widgetptrs; class isofinterest bool operator()( const Widget * pw) const; isofinterest sinteresting; list<widget *>::iterator foundit = find_if ( widgetptrs.begin(), widgetptrs.end(), isinteresting); If ( foundit!= widgetptrs.end() ) // found what I was looking for. 95/134 (c) pk 10

96 Make FOs adaptable. Make FOs adaptable. list<widget *> widgetptrs; class isofinterest bool operator()( const Widget * pw) const; isofinterest sinteresting; list<widget *>::iterator foundit = find_if ( widgetptrs.begin(), widgetptrs.end(), not1(isinteresting)); // ERROR If ( foundit!= widgetptrs.end() ) // found what I was looking for. list<widget *> widgetptrs; class isofinterest : public unary_predicate<widget *,bool> bool operator()( const Widget * pw) const; isofinterest sinteresting; list<widget *>::iterator foundit = find_if ( widgetptrs.begin(), widgetptrs.end(), not1(isinteresting)); If ( foundit!= widgetptrs.end() ) // found what I was looking for. Make FOs adaptable. Conversion Operators list<widget *> widgetptrs; class isactuallybetter : public binary_predicate<widget *, Widget *, bool> bool operator()(const Widget * pw1, const Widget * pw2) const; isactuallybetter isbetter; list<widget *>::iterator foundit = find_if ( widgetptrs.begin(), widgetptrs.end(), bind2nd(isbetter(), mywidget)); If ( foundit!= widgetptrs.end() ) // found what I was looking for. In addition to defining conversions to a class type (using constructors), we can also define conversions from a class type. Why might we need conversion operators? Our own SmallInt? Conversion Operators Do not use conversion operators (unless necessary) Syntax: operator type(); Always a member function class Mystring Usually should be const Mystring(); //convert Mystring to a C-string operator const char * () return s; //... ; int n = strcmp(mystr, C-String"); //OK, automatic conversion of str // to const char * class Rational Public: operator double() const; ; Rational r(1,2); double d = 0.5 *r; cout << r << \t << d << endl class Rational Public: operator asdouble() const; ; Rational r(1,2); double d = 0.5 *r; cout << r << \t << d << endl 96/134 (c) pk 11

97 Conversion operators Conversion operators template<class T> class Array Array (int lb, int hb); Array (int size); T& operator[] (int index); bool operator==(const Array<int>& lhs, const Array<int>& rhs); Array<int> a(10); Array<int> b(10); for (int i = 0; i < 10; ++i) if ( a == b[i] ) template<class T> class Array Array (int lb, int hb); Array (int size); T& operator[] (int index); bool operator==(const Array<int>& lhs, const Array<int>& rhs); Array<int> a(10); Array<int> b(10); for (int i = 0; i < 10; ++i) if ( a == b[i] ) Converted to : if (a == static_cast< Array<int> > (b(i))!! Function objects revisited Conversion operators Design function objects for pass-byvalue Template< class InputIterator, class Function > Function for_each(inputiterator first, InputIterator last, Function f); Keep them small, and don t inherit them. Only one class-type conversion is applied by the compiler. (else, compile time error) Used carefully, class-type conversions can greatly simplify code. Used too freely, they can lead to mysterious errors. Section , and omitted. Reading assignment: Chapter /134 (c) pk 12

98 OOP Object Oriented Programming Object 2 Object 1 Object 3 For : COP Object oriented Programming (Using C++) Object 4 Piyush Kumar Objects: State (fields), Behavior (member functions), Identity Class : Blue print of an object. Data and behavior are strongly linked in OOP. Objects are responsible for their behavior. Example: Complex numbers, Rational numbers, Floating point numbers, all understand addition. OOP components Recap: ADTs Data Abstraction Information Hiding, ADTs Encapsulation Type Extensibility Operator Overloading Inheritance Code Reuse Polymorphism specify the meaning of the operations independent of any implementation/definition. Least common denominator of all possible implementations. Information Hiding: Do not expose unnecessary information. Inheritance Inheritance Two example classes Class Employee Two example classes Class Manager class Employee Employee(string thename, float PayRate); string Name() const; float PayRate() const; float compute_pay(float hoursworked) const; protected: string name; float payrate; ; class Manager Manager(string thename, float PayRate); void set_manages(int n); string Name() const; float PayRate() const; float compute_pay(float hoursworked) const; protected: string name; float payrate; int manages_n_employees; ; 98/134 (c) pk 1

99 Reuse Manager We have done unnecessary work to create Manager, which is similar to (and really is a is a") Employee. We can fix this using the OO concept of inheritance. We let a manager inherit from an employee. A manager gets all the data and functionality of an employee after inheritance. We can then add any new data and methods needed for a manager and redefine any methods that differ for a manager. class Manager : public Employee // is a relationship Manager(string thename, float PayRate, int n); void set_manages(int n); protected: int manages_n_employees; ; Methods of Manager have access to name, payrate because they were declared in Employee as "protected. More on Inheritance : Access privileges. In a public inheritance: Public members are accessible to derived class. Protected members are accessible to derived class. These members are not accessible to the users of the base class. But private are not. Inheritance Derive a new class (subclass) from an existing class (base class). Syntax: class classname : access-label base-class Access-labels = public, private, protected Inheritance creates a hierarchy of related classes (types) which share code and interface. More Examples More Examples Base Class Student Shape Loan Derived Classes GradStudent UnderGradStudent Circle Triangle Rectangle Tetrahedron CarLoan HomeImprovementLoan MortgageLoan GradStudent Student UnderGradStudent Person Employee Non-Faculty Faculty Tenure Teaching Is a relationships. 99/134 (c) pk 2

100 Inheritance: Subclass Inheritance Code reuse derive GradStudent from Student (also adds fields/methods) Specialization: Customization derive bounded-stack from stack (by overriding/redefining push) Generalization: Factoring Commonality Avoid code-duplications (why?) Derived classes contain their base classes as subobjects. Manager object. string name; float payrate; int manages_n_employees; Functions in the derived may use members from the base. Employee object There is no requirement that the compiler lay out the base and derived parts of an object contiguously. Inheritance Open-Closed principle in OOP A class must be defined to be used as a base class. A derived class can be used as a baseclass. Forward declarations are same for baseclasses as well as derived classes. class Manager; class Employee; class Manager: public employee; // Error The open/closed principle states that a class must be both open and closed. Open: means it has the ability to be extended Closed: means it cannot be modified other than by extension. Open-Closed Principle Open-Closed principle in OOP Open for extension Closed for modification An interesting paper: The idea is that once a class has been approved for use having gone through code reviews, unit tests, and other qualifying procedures, you don't want to change the class very much, just extend it. 100/134 (c) pk 3

101 Example : Open-Closed Pr. More on Inheritance Queue DeltaBoundedQueue TestQueue Client (Composition) Subclass (Inheritance) TestBoundedQueue A pointer to a derived class can always be used as a pointer to a base class when public inheritance is used. (But not vice-versa) Private base classes are different STL Containers which need to contain both base/derived classes should be made of pointers to base classes. Otherwise : Slicing problem. Virtual Methods A base class must indicate which of its member functions it intends its derived classes to redefine. These member functions are defined as virtual in the base class. Example Base *bp; Derived d; bp = &d; bp->print(); // invokes class Base int i; virtual void print() cout << "i value is " <<i << " inside object of type Base\n\n"; ; class Derived: public Base virtual void print() cout << "i value is " <<i << " inside object of type Derived\n\n"; ; Dynamic Binding Dynamic Vs Static Binding Allows invocation of general methods using a base class pointer. The fact that a reference or pointer might refer to either a base or derivedclass object is the key to dynamic binding. Allows easy extensibility. Static Binding: The compiler uses the type of the pointer to find out which method to call. Dynamic Binding: The decision is made at runtime. (uses virtual keyword) 101/134 (c) pk 4

102 Dynamic Vs Static Binding Static Binding Less time and space overhead. Inlining possible Dynamic Binding Extensibility Better code-reuse. Dynamic Vs Static Binding Efficiency Vs Flexibility Static Binding More efficient Less time and space overhead, can use inlining. Dynamic Binding Flexible: Enables extension of behavior of a system easily. Virtual Functions Have a fixed interface. Derived implementations can change. Dispatched using object s dynamic type to select the appropriate method. Once Virtual, always virtual rule. Once a base-class defines a function as virtual, it remains virtual through out the inheritance hierarchy. An example base class // Item sold at an undiscounted price // derived classes will define various discount strategies class Item_base friend std::istream& operator>>(std::istream&, Item_base&); friend std::ostream& operator<<(std::ostream&, const Item_base&); virtual Item_base* clone() const return new Item_base(*this); Item_base(const std::string &book = "", double sales_price = 0.0): isbn(book), price(sales_price) std::string book() const return isbn; // returns total sales price for a specified number of items // derived classes will override and apply different discount algorithms virtual double net_price(std::size_t n) const return n * price; // no work, but virtual destructor needed // if base pointer that points to a derived object is ever deleted virtual ~Item_base() // Always virtual. Why? (Hint: Static Vs Dynamic Binding) private: std::string isbn; // identifier for the item protected: double price; // normal, undiscounted price ; Scoping rules Scoping Rules. Out of scope of this class. Do not use. In a public base class, public and protected members of the base class remain public and protected members of the derived class. Example: class circle: public point circle c; //can call point::move(int,int) c.move(1,2); Private derivation: public base class members are private in derived class. Example: class stack: private linkedlist stack s; s.insert(1,2); cannot call linkedlist::insert(int,int) Protected derivation: public base class members are protected in derived class. 102/134 (c) pk 5

103 Is a Vs Has a OOP Shape Example Inheritance Considered an Is a class relationship shape e.g.: An HourlyEmployee is a Employee A Convertible is a Automobile A class contains objects of another class as it s member data Considered a Has a class relationship e.g.: One class has a object of another class as it s data rectangle triangle circle Public inheritance: Is A relationships Abstract Base class: Shape. C++ Shape example class Shape Shape ( Point2d& position, Color& c) : center_(position), color_ (c) ; virtual void rotate( double radians ) = 0; virtual bool draw(screen &) = 0; virtual ~Shape(void) = 0; void move(point2d& p) _center = p; ; private: Point2d center_; Color color_; ; class Triangle: public Shape Triangle( Point2d& p[3] ); virtual void rotate ( double radians ) virtual bool draw(screen &s) ; virtual ~Triangle(void) ; private: ; Point2d vertices[3]; Color color_; 103/134 (c) pk 6

104 OOP components Inheritance For : COP Object oriented Programming (Using C++) Data Abstraction Information Hiding, ADTs Encapsulation Type Extensibility Operator Overloading Inheritance Code Reuse Polymorphism Piyush Kumar Is a Vs Has a Another Example UML Vehicle Inheritance Considered an Is a class relationship e.g.: An HourlyEmployee is a Employee A Convertible is a Automobile A class contains objects of another class as it s member data Considered a Has a class relationship e.g.: One class has a object of another class as it s data class Car : public Vehicle //... ; We state the above relationship in several ways: * Car is "a kind of a" Vehicle * Car is "derived from" Vehicle * Car is "a specialized" Vehicle * Car is the "subclass" of Vehicle * Vehicle is the "base class" of Car * Vehicle is the "superclass" of Car (this not as common in the C++ community) Car Virtual Functions Virtual Destructor rule Virtual means overridable Runtime system automatically invokes the proper member function. Costs 10% to 20% extra overhead compared to calling a non-virtual function call. If a class has one virtual function, you want to have a virtual destructor. A virtual destructor causes the compiler to use dynamic binding when calling the destructor. Constructors: Can not be virtual. You should think of them as static member functions that create objects. 104/134 (c) pk 1

105 Pure virtual. A pure virtual member function is a member function that the base class forces derived classes to provide. A pure virtual function makes a class an abstract base class (ABC) Can not be instantiated! An ABC can also have a pure virtual destructor. Pure virtual member functions. Specified by writing =0 after the function parameter list. OOP Shape Example Abstract Base class: Shape. rectangle shape triangle ABC circle class Shape Shape ( Point2d& position, Color& c) : center_(position), color_ (c) ; virtual void rotate( double radians ) = 0; virtual bool draw(screen &) = 0; // Inheritance of interface. virtual ~Shape(void) = 0; virtual void error(const string& msg); // Inheritance of implementation. int ObjectID() const; // Do not redefine. void move(point2d& p) _center = p; ; private: Point2d center_; Color color_; ; Public inheritance: Is A relationships C++ Shape example Concrete derived class class Triangle: public Shape Triangle( Point2d& p[3] ); virtual void rotate ( double radians ) virtual bool draw(screen &s) ; virtual ~Triangle(void) ; // Can use the default error // Must not define / declare ObjectID Has no pure virtual functions. Simply provides the definition of all the pure virtual functions in its ABC. private: ; Point2d vertices[3]; 105/134 (c) pk 2

106 Typecasts Containers and Inheritance Can I convert a pointer of a derived class type to a base class type?? Does it require a typecast? Because derived objects are sliced down when assigned to a base object, containers and types related by inheritance do not mix well. multiset<item_base> basket; Item_base base; Bulk_item bulk; basket.insert(base); basket.insert(bulk); // problem! (Slicing!) Questions Inheritance How can a class Y be a kind-of another class X as well as get the bits of X? Is-a relationship How can a class Y get the bits of X without making Y a kind-of X? Has a relationship Except for friendship, inheritance is the strongest relationship that can be expressed in C++, and should be only be used when it's really necessary. Multiple Inheritance Multiple inheritance refers to a feature of object-oriented programming languages in which a class can inherit behaviors and features from more than one superclass. Multiple inheritance can cause some confusing situations (A Diamond!) Java compromises. (can inherit implementation from only one parent). Virtual inheritance is used to solve problems caused by MI. Virtual and Multiple Inheritance Multiple and virtual Inheritance: Beyond the scope of this class. 106/134 (c) pk 3

107 Polymorphism Polymorphism. Literal meaning : Many forms We can use the many forms of derived and base classes interchangeably. The fact that static and dynamic types of references and pointers can differ is the cornerstone of how C++ supports polymorphism. C++ supports several kinds of static (compiletime) and dynamic (run-time) polymorphism. Static Polymorphism Function/Operator Overloading Class/function templates Dynamic polymorphism Polymorphism through inheritance/virtual member functions Polymorphism : Example #include <iostream> class Bird // the "generic" base class virtual void OutputName() std::cout << "a bird"; virtual ~Bird() ; class Swan : public Bird // Swan derives from Bird void OutputName() std::cout << "a swan"; // overrides virtual function ; int main() Bird* mybird = new Swan; // Declares a pointer to a generic Bird, // and sets it pointing to a newly-created Swan. mybird->outputname(); // This will output "a swan", not "a bird". delete mybird; return 0; RTTI: Run time type identification. C++ has the ability to determine the type of a program's object/variable at runtime. class base virtual ~base() ; class derived : public base virtual ~derived() int compare (derived &ref); ; int my_comparison_method_for_generic_sort (base &ref1, base &ref2) derived & d = dynamic_cast<derived &>(ref1); // rtti used here // rtti enables the process to throw a bad_cast exception // if the cast is not successful return d.compare (dynamic_cast<derived &>(ref2)); Inheritance Guidelines Inheritance Prefer minimal classes. D&C: Small classes are easier to write, get right, test, use Prefer composition to inheritance. Avoid inheriting from classes that were not designed to be base classes. Prefer providing abstract interfaces. Differentiate between inheritance of interface and inheritance of implementation Member function interfaces are always inherited. Purpose of pure virtual function is to have derived classes inherit a function interface only. Purpose of declaring a simple virtual function is to have derived classes inherit a function interface as well as a default implementation. Purpose of non-virtual function is to have a derived class inherit a function interface as well as a mandatory implementation. 107/134 (c) pk 4

108 Inheritance Inheritance and templates. Never redefine an inherited non-virtual function. Never redefine an inherited default parameter value. Virtual functions are dynamically bound but default parameter values are statically bound. Consider the two design problems A stack of objects. Each stack is homogeneous. You might have a stack of ints, strings, Classes representing monkeys. You need several different classes representing monkeys (each breed is a little different). Sound similar? They result in utterly different software design. Inheritance and templates. With both stacks and monkeys, you are dealing with variety of different types. (objects of type T, monkeys of breed T) Question you want to ask yourself: Does the type T affect the behavior of the class? Nope : Use templates Yup: You need virtual functions? Some real interview questions. What is an explicit constructor? What is a mutable member? Explain the ISA and Has-A class relationships. How would you implement each in a class design? What is a virtual destructor? What is the difference between a copy constructor and an overloaded assignment operator? Your next assignment. BigNumber BigNumber class BigNumber const int bitsize = 128; // All derived numbers should work upto 128 bits. virtual void print(); // prints the value of the number to cout BigInteger BigRational virtual ~BigNumber(); Operators overloaded: <<, +, *, >> (Left and right shift) Provide other functions in your interface as needed. Operator+ and * should work for mixed type arithmetic. 108/134 (c) pk 5

109 Your library should Graph libraries BigInteger i1(7); //default bit length = 128bits BigRational r2(32,7); //represents 32/7 BigInteger & n1 = i1; BigRational & n2 = r2; BigRational n3 = n1 * n2; // n3 should be a Rational // whose value is 32 n1 = (n1 + n3) + n1; // n1 should be an Integer // n1 = = 46 cout << n3 << endl; cout << n2 << endl; cout << ((n1 + 1) >> 1) << endl; // 4 now LEDA Boost Graph Deadline: Nov 20 th. 11am Next homework: BFS on Graphs. Start designing your graph data structure class in C++. You need to submit the spec sheet in the beginning of class on Nov 14 th. 109/134 (c) pk 6

110 Contents Profiling tools Piyush Kumar for COP Introduction Software optimization process, optimization traps and pitfalls Tests / Benchmark Performance tools overview Optimizing compilers System Performance monitors Profiling tools GNU gprof Valgrind What does it mean to use system efficiently Slide source : Vitaly Kroivets Profiling Tools 1 Profiling Tools 2 The Problem PC speed increased 500 times since 1981, but today s software is more complex and still hungry for more resources How to run faster on same hardware and OS architecture? Highly optimized applications run tens times faster than poorly written ones. Using efficient algorithms and well-designed implementations leads to high performance applications The Software Optimization Process Create tests/benchmark Retest using benchmark Find hotspots Modify application Hotspots are areas in your code that take a long time to execute Investigate causes Profiling Tools 3 Profiling Tools 4 Extreme Optimization Pitfalls Large application s performance cannot be improved before it runs Build the application then see what machine it runs on Runs great on my computer Debug versus release builds Performance requires assembly language programming Code features first then optimize if there is time leftover Key Point: Corollary: Premature optimization is root of all evil. Software optimization doesn t begin where coding ends It is ongoing process that starts at design stage and continues all the way through development Profiling Tools 5 Profiling Tools 6 110/134 (c) pk 1

111 Attributes of good tests/benchmark Tests / Benchmarks Implement before you touch your code. Repeatable (consistent measurements) Remember system tasks, caching issues use minimum performance number? Representative Execution of typical code path, mimic how customer uses the application Poor benchmarks : Using QA tests Profiling Tools 7 Profiling Tools 8 Test/Benchmark attributes (cont.) Easy to run Verifiable Measure Elapsed Time vs. other number Use benchmark to test functionality Algorithmic tricks to gain performance may break the application How to find performance bottlenecks Determine how your system resources, such as memory and processor, are being utilized to identify system-level bottlenecks Measure the execution time for each module and function in your application Determine how the various modules running on your system affect the performance of each other Identify the most time-consuming function calls and call sequences within your application Determine how your application is executing at the processor level to identify microarchitecture-level performance problems Profiling Tools 9 Profiling Tools 10 Performance Tools Overview Using Optimizing Compilers Timing mechanisms Stopwatch : UNIX time tool Optimizing compiler (easy way) System load monitors vmstat, iostat, perfmon.exe, Vtune Counter, top Software profiler Gprof, VTune, Visual C++ Profiler, IBM Quantify Memory debugger/profiler Valgrind, IBM Purify, Parasoft Insure++ Always use compiler optimization settings to build an application for use with performance tools Understanding and using all the features of an optimizing compiler is required for maximum performance with the least effort Profiling Tools 11 Profiling Tools /134 (c) pk 2

112 Optimizing Compiler : choosing optimization flags combination Optimizing Compiler s effect Profiling Tools 13 Profiling Tools 14 Optimizing Compilers: Conclusions Profilers Some processor-specific options still do not appear to be a major factor in producing fast code More optimizations do not guarantee faster code Different algorithms are most effective with different optimizations Idea : use statistics gathered by profiler as input for compiler/linker Profiler may show time elapsed in each function and its descendants number of calls, call-graph (some) Profilers use either instrumentation or sampling to identify performance issues Profiling Tools 15 Profiling Tools 16 Sampling vs. Instrumentation Profiling Tools Overhead System-wide profiling Detect unexpected events Setup Data collected Data granularity Detects algorithmic issues Sampling Typically about 1% Yes, profiles all app, drivers, OS functions Yes, can detect other programs using OS resources None Counters, processor an OS state Assembly level instr., with src line No, Limited to processes, threads Instrumentation High, may be 500%! Just application and instrumented DLLs No Automatic ins. of data collection stubs required Call graph, call times, critical path Functions, sometimes statements Yes can see algorithm, call path is expensive Gprof Prof (less extensive than gprof) Valgrind Old, buggy and inaccurate Is not profiler really man gcov/gprof/prof Profiling Tools 17 Profiling Tools /134 (c) pk 3

113 Using gprof GNU profiler GNU gprof Instrumenting profiler for every UNIXlike system Compile and link your program with profiling enabled cc -g -c myprog.c utils.c -pg cc -o myprog myprog.o utils.o -pg Execute your program to generate a profile data file Program will run normally (but slower) and will write the profile data into a file called gmon.out just before exiting Program should exit using exit() function Run gprof to analyze the profile data gprof a.out Profiling Tools 19 Profiling Tools 20 Example Program Understanding Flat Profile The flat profile shows the total amount of time your program spent executing each function. If a function was not compiled for profiling, and didn't run long enough to show up on the program counter histogram, it will be indistinguishable from a function that was never called Profiling Tools 21 Profiling Tools 22 Flat profile : %time Flat profile: Cumulative seconds This is cumulative total number of seconds the spent in this functions, plus the time spent in all the functions above this one Percentage of the total execution time your program spent in this function. These should all add up to 100%. Profiling Tools 23 Profiling Tools /134 (c) pk 4

114 Flat profile: Self seconds Flat profile: Calls Number of seconds accounted for this function alone Number of times was invoked Profiling Tools 25 Profiling Tools 26 Flat profile: Self seconds per call Average number of sec per call Spent in this function alone Flat profile: Total seconds per call Average number of seconds spent in this function and its descendents per call Profiling Tools 27 Profiling Tools 28 Call Graph : call tree of the program Call Graph : understanding each line Called by : main ( ) Unique index of this function Total time propagated into this function by its children Number of times was called Current Function: g( ) Current Function: g( ) Descendants: doit ( ) Profiling Tools 29 Percentage of the `total time spent in this function and its children. total amount of time spent in this function Profiling Tools /134 (c) pk 5

115 Call Graph : parents numbers Call Graph : children numbers Time that was propagated from the function's children into this parent Call Graph : understanding function each was called line Time that was propagated directly from the function into this parent Number of times this parent called the function `/ total number of times the Current Function: g( ) Number of times this function called the child `/ total number of times this child was called Current Function: g( ) Amount of time that was propagated directly from the child into function Profiling Tools 31 Amount of time that was propagated from the child's children to the function Profiling Tools 32 How gprof works Instruments program to count calls Watches the program running, samples the PC every 0.01 sec Statistical inaccuracy : fast function may take 0 or 1 samples Run should be long enough comparing with sampling period Combine several gmon.out files into single report The output from gprof gives no indication of parts of your program that are limited by I/O or swapping bandwidth. This is because samples of the program counter are taken at fixed intervals of run time number-of-calls figures are derived by counting, not sampling. They are completely accurate and will not vary from run to run if your program is deterministic Profiling with inlining and other optimizations needs care Valgrind Multi-purpose Linux x86 profiling tool Profiling Tools 33 Profiling Tools 34 Valgrind Toolkit Memcheck Features Memcheck is memory debugger detects memory-management problems Cachegrind is a cache profiler performs detailed simulation of the I1, D1 and L2 caches in your CPU Massif is a heap profiler performs detailed heap profiling by taking regular snapshots of a program's heap Helgrind is a thread debugger finds data races in multithreaded programs When a program is run under Memcheck's supervision, all reads and writes of memory are checked, and calls to malloc/new/free/delete are intercepted Memcheck can detect: Use of uninitialised memory Reading/writing memory after it has been free'd Reading/writing off the end of malloc'd blocks Reading/writing inappropriate areas on the stack Memory leaks -- where pointers to malloc'd blocks are lost forever Passing of uninitialised and/or unaddressible memory to system calls Mismatched use of malloc/new/new [] vs free/delete/delete [] Overlapping src and dst pointers in memcpy() and related functions Some misuses of the POSIX pthreads API Profiling Tools 35 Profiling Tools /134 (c) pk 6

116 Memcheck Example Memcheck Example (Cont.) Access of unallocated memory Using noninitialized value Compile the program with g flag: g++ -c a.cc g o a.out Execute valgrind : Debug leaks valgrind --tool=memcheck --leak-check=yes a.out > log Memory leak Using free of memory allocated by new View log Executable name Profiling Tools 37 Profiling Tools 38 Memcheck report Memcheck report (cont.) Leaks detected: S T A C K Profiling Tools 39 Profiling Tools 40 Cachegrind How to run Detailed cache profiling can be very useful for improving the performance of the program On a modern x86 machine, an L1 miss will cost around 10 cycles, and an L2 miss can cost as much as 200 cycles Cachegrind performs detailed simulation of the I1, D1 and L2 caches in your CPU Can accurately pinpoint the sources of cache misses in your code Identifies number of cache misses, memory references and instructions executed for each line of source code, with perfunction, per-module and whole-program summaries Cachegrind runs programs about x slower than normal Run valgrind --tool=cachegrind in front of the normal command line invocation Example : valgrind --tool=cachegrind ls -l When the program finishes, Cachegrind will print summary cache statistics. It also collects line-by-line information in a file cachegrind.out.pid Execute cg_annotate to get annotated source file: Source files cg_annotate a.cc > a.cc.annotated Profiling Tools 41 PID Profiling Tools /134 (c) pk 7

117 Cachegrind Summary output Cachegrind Summary output I-cache reads (instructions executed) I1 cache read misses Instruction caches performance D-cache reads (memory reads) D1 cache read misses Data caches READ performance L2-cache instruction read misses L2-cache data read misses Profiling Tools 43 Profiling Tools 44 Cachegrind Summary output Cachegrind Accuracy D-cache writes (memory writes) L2-cache data write misses D1 cache write misses Data caches WRITE performance Valgrind's cache profiling has a number of shortcomings: It doesn't account for kernel activity -- the effect of system calls on the cache contents is ignored It doesn't account for other process activity (although this is probably desirable when considering a single program) It doesn't account for virtual-to-physical address mappings; hence the entire simulation is not a true representation of what's happening in the cache Profiling Tools 45 Profiling Tools 46 Massif tool Executing Massif Massif is a heap profiler - it measures how much heap memory programs use. It can give information about: Heap blocks Heap administration blocks Stack sizes Help to reduce the amount of memory the program uses smaller program interact better with caches, avoid paging Detect leaks that aren't detected by traditional leak-checkers, such as Memcheck That's because the memory isn't ever actually lost - a pointer remains to it - but it's not in use anymore Run valgrind tool=massif prog Produces following: Summary Graph Picture Report Summary will look like this: Total spacetime: 2,258,106 ms.b Heap: 24.0% Heap admin: 2.2% Stack (s): 73.7% Space (in bytes) multiplied by time (in milliseconds). number of words allocated on heap, via malloc(), new and new[]. Profiling Tools 47 Profiling Tools /134 (c) pk 8

118 Spacetime Graphs Spacetime Graph (Cont.) Each band represents single line of source code It's the height of a band that's important Triangles on the x-axis show each point at which a memory census was taken Not necessarily evenly spread; Massif only takes a census when memory is allocated or de-allocated The time on the x-axis is wall-clock time not ideal because can get different graphs for different executions of the same program, due to random OS delays Profiling Tools 49 Profiling Tools 50 Text/HTML Report example Valgrind how it works Contains a lot of extra information about heap allocations that you don't see in the graph. Valgrind is compiled into a shared object, valgrind.so. The shell script valgrind sets the LD_PRELOAD environment variable to point to valgrind.so. This causes the.so to be loaded as an extra library to any subsequently executed dynamically-linked ELF binary The dynamic linker allows each.so in the process image to have an initialization function which is run before main(). It also allows each.so to have a finalization function run after main() exits When valgrind.so's initialization function is called by the dynamic linker, the synthetic CPU to starts up. The real CPU remains locked in valgrind.so until end of run Shows places in the program where most memory was allocated System call are intercepted; Signal handlers are monitored Profiling Tools 51 Profiling Tools 52 Valgrind Summary Other Tools Valgrind will save hours of debugging time Valgrind can help speed up your programs Valgrind runs on x86-linux Valgrind works with programs written in any language Valgrind is actively maintained Valgrind can be used with other tools (gdb) Valgrind is easy to use uses dynamic binary translation, so no need to modify, recompile or re-link applications. Just prefix command line with valgrind and everything works Valgrind is not a toy Used by large projects : 25 millions lines of code Valgrind is free Tools not included in this presentation: Intel s Vtune IBM Purify Parasoft Insure KCachegrind Oprofile GCC s and GLIBC s debugging hooks Profiling Tools 53 Profiling Tools /134 (c) pk 9

119 Writing Fast Programs CPU Architecture (Pentium 4) Select right algorithm (Take COP 4531) Implement it efficiently Detect hotspots using profiler and fix them Understanding of target system architecture is often required such as cache structure Use platform-specific compiler extensions memory pre-fetching, cache control-instruction, branch prediction, SIMD instructions Write multithreaded applications ( Hyper Threading Technology ) Instruction fetch Out-of-order Execution! Branch prediction Instruction decode Instruction pool Execution Units Memory retirement Profiling Tools 55 Profiling Tools 56 Instruction Execution Keeping CPU Busy Instruction pool Dispatch unit Execution Units Integer Integer Floating point Floating point Memory Load Memory Save Processors are limited by data dependencies and speed of instructions Keep data dependencies low Good blend of instructions keep all execution units busy at same time Waiting for memory with nothing else to execute is most common reason for slow applications Goals: ready instructions, good mix of instructions and predictable branches Remove branches if possible Reduce randomness of branches, avoid function pointers and jump tables Profiling Tools 57 Profiling Tools 58 Memory Overview (Pentium 4) Fixing memory problems L1 cache (data only) 8 kbytes L2 Advanced Transfer Cache (data + instructions) 256 kbytes, 3 times slower than L1 L3 : 4MB cache (optional) Main RAM (usually 64M 4G), 10 times slower than L1 Use less memory to reduce compulsory cache misses Increase cache efficiency (place items used at same time near each other) Read sooner with prefetch Avoid conflicts Avoid capacity issues Add more work for CPU (execute nondependent instruction while waiting) Profiling Tools 59 Profiling Tools /134 (c) pk 10

120 References SPEC website The Software Optimization Cookbook High-Performance Recipes for the Intel Architecture by Richard Gerber GCC Optimization flags Options.html Valgrind Homepage An Evolutionary Analysis of GNU C Optimizations Using Natural Selection to Investigate Software Complexities by Scott Robert Ladd Intel VTune Performace Analyzer webpage Gprof man page Profiling Tools /134 (c) pk 11

121 An introduction to C++ Templates For : COP Object oriented Programming (Using C++) Templates Are C macros on Steroids Give you the power to parametrize Compile time computation Performance The art of programming programs that read, transform, or write other programs. - François-René Rideau Piyush Kumar Generic Programming Templates How do we implement a linked list with a general type inside? void pointers? Using macros? Using Inheritance? Function Templates Class Templates Template templates * Full Template specialization Partial template specialization Metaprogramming Programs that manipulate other programs or themselves Can be executed at compile time or runtime. Template metaprograms are executed at compile time. Good old C C code Double square(double x) return x*x; sqare(3.14) Computed at compile time #define square(x) ((x)*(x)) Static double sqrarg; #define SQR(a) (sqrarg=(a), sqrarg*sqrarg) 121/134 (c) pk 1

122 Templates Help us to write code without being tied to particular type. Question: How do you swap two elements of any type? How do you return the square of any type? Defining the template min.hpp template <typename T> inline T const& min (T const& a, T const& b) return a < b? a : b ; Template parameter T. Syntax: template < comma separated list of parameters > For historical reasons, you can use class instead of typename. Using the template The process of replacing template parameters with concrete types is called instantiation. A compile time error #include <iostream> #include <string> #include min.hpp inline int const& min(int const& a, int const& b) return a < b? a : b; // The following does not provide operator< std::complex<float> c1,c2; int main() int i = 12; std::cout << min(7,i): << ::min(7,i) << std::endl; std::string s1 = math ; std::string s2 = cs ; std::cout << min(s1,s2): << ::min(s1,s2) << std::endl; min(c1,c2); // error at compile time. Attempt to instantiate a template for a type that doesn t support all the Operations used within it will result in a compile-time error. Function Templates Function Templates C++ template< typename T > inline T square ( T x ) return x*x; A specialization is instantiated if needed : square<double>(3.14) Template arguments maybe deduced from the function arguments square(3.14) MyType m; ; square(m); expands to square<mytype>(m) Operator * must be overloaded for MyType template<typename T> void swap( T& a, T& b ) T tmp(a); // cc required a = b; // ao required b = tmp; Mytype x = 1111; Mytype y = ; swap(x,y); swap<mytype>( ) is instantiated Note reliance on T s concepts (properties): In above, T must be copyable and assignable Compile-time enforcement (concept-checking) techniques available 122/134 (c) pk 2

123 Argument deduction Template Parameters. template <typename T> // T is a template parameter inline T const& min (T const& a, T const& b) // a and b are call parameter. return a < b? a : b ; min(4,7); // ok : T is int for both arguments. min(4,4.2); // error: First T is int, second T is double. Solutions: 1. min ( static_cast<double>(4), 4.2); // ok 2. min<double>(4,4.2); // ok You may have as many template parameters as you like. template <typename T1, typename T2> inline T1 min (T1 const& a, T2 const& b) return a < b? a : b ; min(4,4.2); // ok : but type of first argument defines return type. // drawback : min (4,4.2) is different compared to min(4.2,4) // return is created by an implicit typecast and can not be returned as // a reference. Template parameters. template <typename T1, typename T2, typename RT > inline RT min (T1 const& a, T2 const& b) return static_cast<rt>(a < b? a : b); min<int,double,double>(4,4.2); // ok: but long and tedious template < typename RT, typename T1, typename T2 > inline RT min (T1 const& a, T2 const& b) return static_cast<rt>(a < b? a : b); Function Template Specialization template<> void swap<myclass>( myclass& a, myclass& b) a = b = 0; Custom version of a template for a specific class min<double>(4,4.2); // ok: return type is double. Class Templates Class templates. template<typename NumType, unsigned D> class dpoint NumType x[d]; ; A simple 3-dimensional point. dpoint<float,3> point_in_3d; point_in_3d.x[0] = 5.0; point_in_3d.x[1] = 1.0; point_in_3d.x[2] = 2.0; Implementing a member function. template<typename NumType, unsigned D> class dpoint inline virtual void normalize (void); template<typename NumType, unsigned D> void dpoint<numtype,d>::normalize (void) NumType len = sqrt(sqr_length()); if (len > ) for(unsigned i = 0; i < D; ++i) x[i] /= len; Note the explicit instantiation 123/134 (c) pk 3

124 Friend templates template<typename NumType, unsigned D> class dpoint template<typename NT, unsigned DIM> friend bool operator!= (const dpoint<nt, DIM>& p, const dpoint<nt, DIM>& q); template<typename NT, unsigned DIM> bool operator!= (const dpoint<nt, DIM>& p, const dpoint<nt, DIM>& q) // Member templates. template <typename T> class Stack private: std::deque<t> elems; // elements void push(const T&); // store new top element void pop(); // remove top element T top() const; // return top element bool empty() const // return whether the stack is empty return elems.empty(); // assign stack of elements of type T2 template <typename T2> Stack<T>& operator= (Stack<T2> const&); ; Member Templates template <typename T> template <typename T2> Stack<T>& Stack<T>::operator= (Stack<T2> const& op2) if ((void*)this == (void*)&op2) // assignment to itself? return *this; Stack<T2> tmp(op2); // create a copy of the assigned stack elems.clear(); // remove existing elements while (!tmp.empty()) // copy all elements elems.push_front(tmp.top()); tmp.pop(); return *this; Parameterized container. template <typename T, typename CONT = std::deque<t> > class Stack private: CONT elems; // elements void push(t const&); // push element void pop(); // pop element T top() const; // return top element bool empty() const // return whether the stack is empty return elems.empty(); // assign stack of elements of type T2 template <typename T2, typename CONT2> Stack<T,CONT>& operator= (Stack<T2,CONT2> const&); ; Member template again. Spot the problem template <typename T, typename CONT> template <typename T2, typename CONT2> Stack<T,CONT>& Stack<T,CONT>::operator= (Stack<T2,CONT2> const& op2) if ((void*)this == (void*)&op2) // assignment to itself? return *this; Stack<T2,CONT2> tmp(op2); // create a copy of the assigned stack elems.clear(); // remove existing elements while (!tmp.empty()) // copy all elements elems.push_front(tmp.top()); tmp.pop(); return *this; #include <string> // note: reference parameters template <typename T> inline T const& max (T const& a, T const& b) return a < b? b : a; int main() std::string s; ::max("apple","peach"); // OK ::max("apple","tomato"); // ERROR ::max("apple",s); // ERROR 124/134 (c) pk 4

125 Class Templates: Unlike function templates Class template arguments can t be deduced in the same way, so usually written explicitly: dpoint <double, 2> c; // 2d point Class template parameters may have default values: template< class T, class U = int > class MyCls ; Class templates may be partially specialized: template< class U > class MyCls< bool, U > ; Using Specializations First declare (and/or define) the general case: template< class T > class C /* handle most types this way */ ; Then provide either or both kinds of special cases as desired: template< class T > class C< T * > /* handle pointers specially */ ; template<> // note: fully specialized class C< int * > /* treat int pointers thusly */ ; Compiler will select the most specialized applicable class template Template Template Parameters More Templates A class template can be a template argument Example: template< template<typename ELEM> class Bag > class C // Bag< float > b; ; Or even: template< class E, template<typename ELEM> class Bag > class C // Bag< E > b; ; template<unsigned u> class MyClass enum X = u ; ; Cout << MyClass<2>::X << endl; Template Metaprograms Factorials at compile time template<int N> class Factorial enum value = N * Factorial<N-1>::value ; ; template<> class Factorial<1> enum value = 1 ; ; Template Metaprograms Metaprogramming using C++ can be used to implement a turning machine. (since it can be used to do conditional and loop constructs). int w = Factorial<10>::value; 125/134 (c) pk 5

126 Template Metaprograms Food for thought template< typename NumType, unsigned D, unsigned I > struct origin static inline void eval( dpoint<numtype,d>& p ) p[i] = 0.0; origin< NumType, D, I-1 >::eval( p ); ; // Partial Template Specialization template <typename NumType, unsigned D> struct origin<numtype, D, 0> static inline void eval( dpoint<numtype,d>& p ) p[0] = 0.0; ; You can implement IF WHILE FOR Using metaprogramming. And then use them in your code that needs to run at compile time const int D = 3; inline void move2origin() origin<numtype, D, D-1>::eval(*this); ; For the more challenged: Implement computation of determinant / orientation / volume using metaprogramming. (Extra credit) Template Metaprogramming Examples. Template Metaprogramming examples. /* Fibonacci's Function as C++ Template Metaprogram */ template< unsigned long N > struct Fib enum value = Fib<N-1>::value + Fib<N-2>::value ; ; struct Fib< 1 > enum value = 1 ; ; struct Fib< 2 > enum value = 1 ; ; /* Binary-to-Decimal as Template Metaprogram */ template< unsigned long N > struct Bin enum value = (N % 10) + 2 * Bin< N / 10 > :: value ; ; struct Bin< 0 > enum value = 0 ; ; usigned long const one = binary<1001>::value; More metaprogramming Traits Technique Learn and use the Boost MTL Library. Operate on types instead of data How do you implement a mean class without specifying the types. For double arrays it should output double For integers it should return a float For complex numbers it should return a complex number 126/134 (c) pk 6

127 Traits Traits Template< typename T > struct average_traits typedef T T_average; ; Template<> struct average_traits<int> typedef float T; average_type(t) = T average_type(int) = float Traits Sources template<typename T> typename average_traits<t>::t_average average(t* array, int N) typename avearage_traits<t>::t_average result = sum(array,n); return result/n; C++ Templates: The complete guide by Vandevoorde and Josuttis. Template Metaprogramming by Todd Veldhuizen C++ Meta<Programming> Concepts and results by Walter E. Brown C++ For Game programmers by Noel Llopis C++ Primer by Lippman and Lajoie 127/134 (c) pk 7

128 The user. Advanced C++ For : COP Object oriented Programming (Using C++) #define private public #define protected public #define class struct Source: Lutz Kettner. Piyush Kumar Types of users Const correctness Revision. We can distinguish between to kinds of protection a design can provide: an user that makes occasionally mistakes an user that willingly tries to get around the protection mechanism int* p; int* const q; const int* r; const int* const s; // the pointer, the data it refers to // // the pointer, the data it refers to // int* p; // non-const non-const int* const q; // const non-const const int* r; // non-const const const int* const s; // const const Const declaration This pointer and const. struct A ; const int i; A() : i(42) struct C // hidden parameter: T* const this; void foo(); // hidden parameter: const T* const this; void bar() const; ; 128/134 (c) pk 1

129 Make Temporary Return Objects in C++ Classes Const Make Temporary Return Objects in C++ Classes Const L-values: can be used for the left side of an assignment, they are non-const. R-values: cannot be used for the left side of an assignment.. They are const. For example the post-increment operator requires an l-value, but is itself an r-value. Thus, we cannot write: int i; i++ ++; // second ++ forbidden! Or i++++; Error: error.cpp:5: error: non-lvalue in increment But: struct A A operator++ (int); // the post increment operator ; Now, lets try: A a; a++++; //compiles! Make Temporary Return Objects in C++ Classes Const Empty Classes C++ classes are often empty! It works, because a++ returns a temporary object of type A. But it probably does not do what one would expect. Since the second ++ works on a temporary object, a itself gets only incremented once. We can forbid the second increment explicitly by making the return type, the type of the temporary object, const. This should be considered for all similar temporary return types. struct A // the post increment operator const A operator++ (int); ; #include <iostream> using namespace std; struct X ; int main() cout << sizeof(x) << endl; return 0; Empty Classes Polymorphism #include <iostream> using namespace std; struct X ; class Y:public X ; int main() cout << sizeof(x) << endl; cout << sizeof(y) << endl; return 0; Recap: Ability to associate different specific behaviors with a single generic notation. (Many forms or shapes) What you have seen: Dynamic Polymorphism EBCO: Empty base class Optimization 129/134 (c) pk 2

130 Dynamic Polymorphism Example Static Polymorphism #include "coord.hpp" // concrete geometric object class Circle // - \bfseries not derived from any class class Circle void draw() const; Coord center_of_gravity() const; //... ; // concrete geometric object class Line // - \bfseries not derived from any class class Line void draw() const; Coord center_of_gravity() const; //... ; Static Polymorphism #include "statichier.hpp" #include <vector> // draw any GeoObj template <typename GeoObj> void mydraw (GeoObj const& obj) obj.draw(); // call draw() according to type of object // process distance of center of gravity between two GeoObjs template <typename GeoObj1, typename GeoObj2> Coord distance (GeoObj1 const& x1, GeoObj2 const& x2) Coord c = x1.center_of_gravity() - x2.center_of_gravity(); return c.abs(); // return coordinates as absolute values // draw homogeneous collection of GeoObjs template <typename GeoObj> void drawelems (std::vector<geoobj> const& elems) for (unsigned i=0; i<elems.size(); ++i) elems[i].draw(); // call draw() according to type of element Static Polymorphism int main() Line l; Circle c, c1, c2; mydraw(l); mydraw(c); // mydraw<line>(geoobj&) => Line::draw() // mydraw<circle>(geoobj&) => Circle::draw() distance(c1,c2); // distance<circle,circle>(geoobj1&,geoobj2&) distance(l,c); // distance<line,circle>(geoobj1&,geoobj2&) // std::vector<geoobj*> coll; // ERROR: no heterogeneous // collection possible std::vector<line> coll; // OK: homogeneous collection possible coll.push_back(l); // insert line drawelems(coll); // draw all lines Static Polymorphism All types must be determined at compile time. Heterogeneous collections can no longer be handled transparently. Generated code is potentially faster than dynamic polymorphism. CRTP: Curiously recurring template pattern General class of techniques that consists of passing a derived class as a template argument to one of its own base classes. // The Curiously Recurring Template Pattern (CRTP) class derived : public base<derived> //... ; 130/134 (c) pk 3

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class C++ IO C++ IO All I/O is in essence, done one character at a time For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Concept: I/O operations act on streams

More information

C++ Tour. Administrative Trivia. Administrative Trivia. Your ID. Announcement. Announcement. Daniel Mock, About me: Piyush Kumar

C++ Tour. Administrative Trivia. Administrative Trivia. Your ID. Announcement. Announcement. Daniel Mock, About me: Piyush Kumar Administrative Trivia C++ Tour For : COP 3330. Object oriented Programming (Using C++) http://www.cs.fsu.edu/~piyush/teach/3330 About me: Piyush Kumar Phone: 645-2355 Email: piyush@cs.fsu.edu Office hours:

More information

Introduction to C++ (Extensions to C)

Introduction to C++ (Extensions to C) Introduction to C++ (Extensions to C) C is purely procedural, with no objects, classes or inheritance. C++ is a hybrid of C with OOP! The most significant extensions to C are: much stronger type checking.

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

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

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

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018 C++ Basics Lecture 2 COP 3014 Spring 2018 January 8, 2018 Structure of a C++ Program Sequence of statements, typically grouped into functions. function: a subprogram. a section of a program performing

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

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

C++ Input/Output: Streams

C++ Input/Output: Streams C++ Input/Output: Streams Basic I/O 1 The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams:

More information

I/O Streams and Standard I/O Devices (cont d.)

I/O Streams and Standard I/O Devices (cont d.) Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore how to read data from the standard input device Learn how to use predefined

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 The C++ standard libraries provide an extensive set of input/output capabilities. C++ uses type-safe I/O. Each I/O operation is executed in a manner sensitive to the data type. If an I/O member function

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

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia New exercise posted yesterday afternoon, due Monday morning - Read a directory

More information

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords. Chapter 1 File Extensions: Source code (cpp), Object code (obj), and Executable code (exe). Preprocessor processes directives and produces modified source Compiler takes modified source and produces object

More information

Chapter 12 - C++ Stream Input/Output

Chapter 12 - C++ Stream Input/Output Chapter 12 - C++ Stream Input/Output 1 12.1 Introduction 12.2 Streams 12.2.1 Classic Streams vs. Standard Streams 12.2.2 iostream Library Header Files 12.2.3 Stream Input/Output Classes and Objects 12.3

More information

Chapter 3 - Notes Input/Output

Chapter 3 - Notes Input/Output Chapter 3 - Notes Input/Output I. I/O Streams and Standard I/O Devices A. I/O Background 1. Stream of Bytes: A sequence of bytes from the source to the destination. 2. 2 Types of Streams: i. Input Stream:

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

INTERMEDIATE SOFTWARE DESIGN SPRING 2011 ACCESS SPECIFIER: SOURCE FILE

INTERMEDIATE SOFTWARE DESIGN SPRING 2011 ACCESS SPECIFIER: SOURCE FILE HEADER FILE A header (.h,.hpp,...) file contains Class definitions ( class X {... }; ) Inline function definitions ( inline int get_x() {... } ) Function declarations ( void help(); ) Object declarations

More information

CS2141 Software Development using C/C++ Stream I/O

CS2141 Software Development using C/C++ Stream I/O CS2141 Software Development using C/C++ Stream I/O iostream Two libraries can be used for input and output: stdio and iostream The iostream library is newer and better: It is object oriented It can make

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types. The C++ Language Input and Output Output! Output is information generated by a program.! Frequently sent the screen or a file.! An output stream is used to send information. Another type supplied by C++

More information

Streams - Object input and output in C++

Streams - Object input and output in C++ Streams - Object input and output in C++ Dr. Donald Davendra Ph.D. Department of Computing Science, FEI VSB-TU Ostrava Dr. Donald Davendra Ph.D. (Department of Computing Streams - Object Science, input

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

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

Module C++ I/O System Basics

Module C++ I/O System Basics 1 Module - 36 C++ I/O System Basics Table of Contents 1. Introduction 2. Stream classes of C++ 3. Predefined Standard Input/Output Streams 4. Functions of class 5. Functions of class

More information

Fall 2017 CISC/CMPE320 9/27/2017

Fall 2017 CISC/CMPE320 9/27/2017 Notices: CISC/CMPE320 Today File I/O Text, Random and Binary. Assignment 1 due next Friday at 7pm. The rest of the assignments will also be moved ahead a week. Teamwork: Let me know who the team leader

More information

CSE 333 Lecture 9 - intro to C++

CSE 333 Lecture 9 - intro to C++ CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia & Agenda Main topic: Intro to C++ But first: Some hints on HW2 Labs: The

More information

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers. cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... today: language basics: identifiers, data types, operators, type conversions, branching and looping, program structure

More information

CS2141 Software Development using C/C++ Compiling a C++ Program

CS2141 Software Development using C/C++ Compiling a C++ Program CS2141 Software Development using C/C++ Compiling a C++ Program g++ g++ is the GNU C++ compiler. A program in a file called hello.cpp: #include using namespace std; int main( ) { cout

More information

Stream States. Formatted I/O

Stream States. Formatted I/O C++ Input and Output * the standard C++ library has a collection of classes that can be used for input and output * most of these classes are based on a stream abstraction, the input or output device is

More information

Streams. Parsing Input Data. Associating a File Stream with a File. Conceptual Model of a Stream. Parsing. Parsing

Streams. Parsing Input Data. Associating a File Stream with a File. Conceptual Model of a Stream. Parsing. Parsing Input Data 1 Streams 2 Streams Conceptual Model of a Stream Associating a File Stream with a File Basic Stream Input Basic Stream Output Reading Single Characters: get() Skipping and Discarding Characters:

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 21 - C++ Stream Input/Output

Chapter 21 - C++ Stream Input/Output Chapter 21 - C++ Stream Input/Output Outline 21.1 Introduction 21.2 Streams 21.2.1 Iostream Library Header Files 21.2.2 Stream Input/Output Classes and Objects 21.3 Stream Output 21.3.1 Stream-Insertion

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

Chapter 2. Procedural Programming

Chapter 2. Procedural Programming Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic

More information

C Compilation Model. Comp-206 : Introduction to Software Systems Lecture 9. Alexandre Denault Computer Science McGill University Fall 2006

C Compilation Model. Comp-206 : Introduction to Software Systems Lecture 9. Alexandre Denault Computer Science McGill University Fall 2006 C Compilation Model Comp-206 : Introduction to Software Systems Lecture 9 Alexandre Denault Computer Science McGill University Fall 2006 Midterm Date: Thursday, October 19th, 2006 Time: from 16h00 to 17h30

More information

Bruce Merry. IOI Training Dec 2013

Bruce Merry. IOI Training Dec 2013 IOI Training Dec 2013 Outline 1 2 3 Outline 1 2 3 You can check that something is true using assert: #include int main() { assert(1 == 2); } Output: test_assert: test_assert.cpp:4: int main():

More information

Streams in C++ Stream concept. Reference information. Stream type declarations

Streams in C++ Stream concept. Reference information. Stream type declarations Stream concept A stream represent a sequence of bytes arriving, being retrieved, being stored, or being sent, in order. A stream is continuos and offer sequential access to the data. Each byte can be read

More information

C++ Quick Guide. Advertisements

C++ Quick Guide. Advertisements C++ Quick Guide Advertisements Previous Page Next Page C++ is a statically typed, compiled, general purpose, case sensitive, free form programming language that supports procedural, object oriented, and

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

G52CPP C++ Programming Lecture 9

G52CPP C++ Programming Lecture 9 G52CPP C++ Programming Lecture 9 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture const Constants, including pointers The C pre-processor And macros Compiling and linking And

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

Unit 1 : Principles of object oriented programming

Unit 1 : Principles of object oriented programming Unit 1 : Principles of object oriented programming Difference Between Procedure Oriented Programming (POP) & Object Oriented Programming (OOP) Divided Into Importance Procedure Oriented Programming In

More information

VALLIAMMAI ENGINEERING COLLEGE

VALLIAMMAI ENGINEERING COLLEGE VALLIAMMAI ENGINEERING COLLEGE SRM Nagar, Kattankulathur 603 203 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING QUESTION BANK B.E. - Electrical and Electronics Engineering IV SEMESTER CS6456 - OBJECT ORIENTED

More information

Overview of Compiler. A. Introduction

Overview of Compiler. A. Introduction CMPSC 470 Lecture 01 Topics: Overview of compiler Compiling process Structure of compiler Programming language basics Overview of Compiler A. Introduction What is compiler? What is interpreter? A very

More information

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING Dr. Shady Yehia Elmashad Outline 1. Introduction to C++ Programming 2. Comment 3. Variables and Constants 4. Basic C++ Data Types 5. Simple Program: Printing

More information

Week 3: File I/O and Formatting 3.7 Formatting Output

Week 3: File I/O and Formatting 3.7 Formatting Output Week 3: File I/O and Formatting 3.7 Formatting Output Formatting: the way a value is printed: Gaddis: 3.7, 3.8, 5.11 CS 1428 Fall 2014 Jill Seaman spacing decimal points, fractional values, number of digits

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

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

More information

UEE1303(1070) S 12 Object-Oriented Programming in C++

UEE1303(1070) S 12 Object-Oriented Programming in C++ Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1303(1070) S 12 Object-Oriented Programming in C++ Lecture 06: Streams and File Input/Output I/O stream istream and ostream member

More information

6.096 Introduction to C++ January (IAP) 2009

6.096 Introduction to C++ January (IAP) 2009 MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Streams. Rupesh Nasre.

Streams. Rupesh Nasre. Streams Rupesh Nasre. OOAIA January 2018 I/O Input stream istream cin Defaults to keyboard / stdin Output stream ostream cout std::string name; std::cout > name; std::cout

More information

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING CS6456 OBJECT ORIENTED PROGRAMMING

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING CS6456 OBJECT ORIENTED PROGRAMMING DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING CS6456 OBJECT ORIENTED PROGRAMMING Unit I : OVERVIEW PART A (2 Marks) 1. Give some characteristics of procedure-oriented

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

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

Software Design & Programming I

Software Design & Programming I Software Design & Programming I Starting Out with C++ (From Control Structures through Objects) 7th Edition Written by: Tony Gaddis Pearson - Addison Wesley ISBN: 13-978-0-132-57625-3 Chapter 3 Introduction

More information

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program

More information

Reliable C++ development - session 1: From C to C++ (and some C++ features)

Reliable C++ development - session 1: From C to C++ (and some C++ features) Reliable C++ development - session 1: From C to C++ (and some C++ features) Thibault CHOLEZ - thibault.cholez@loria.fr TELECOM Nancy - Université de Lorraine LORIA - INRIA Nancy Grand-Est From Nicolas

More information

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University (5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University Key Concepts 2 Object-Oriented Design Object-Oriented Programming

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

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

Chapter 21 - C++ Stream Input/Output

Chapter 21 - C++ Stream Input/Output Chapter 21 - C++ Stream Input/Output Outline 21.1 Introduction 21.2 Streams 21.2.1 Iostream Library Header Files 21.2.2 Stream Input/Output Classes and Objects 21.3 Stream Output 21.3.1 Stream-Insertion

More information

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved. Chapter 12 Streams and File I/O Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output, flag

More information

BITG 1233: Introduction to C++

BITG 1233: Introduction to C++ BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token

More information

CS201 Solved MCQs.

CS201 Solved MCQs. 15.1 Answer each of the following: a. Input/output in C++ occurs as of bytes. b. The stream manipulators that format justification are, and. c. Member function can be used to set and reset format state.

More information

Computer Programming : C++

Computer Programming : C++ The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program

More information

COMP322 - Introduction to C++

COMP322 - Introduction to C++ COMP322 - Introduction to C++ Lecture 05 - I/O using the standard library, stl containers, stl algorithms Dan Pomerantz School of Computer Science 5 February 2013 Basic I/O in C++ Recall that in C, we

More information

Basic Types, Variables, Literals, Constants

Basic Types, Variables, Literals, Constants Basic Types, Variables, Literals, Constants What is in a Word? A byte is the basic addressable unit of memory in RAM Typically it is 8 bits (octet) But some machines had 7, or 9, or... A word is the basic

More information

Lecture 03 Bits, Bytes and Data Types

Lecture 03 Bits, Bytes and Data Types Lecture 03 Bits, Bytes and Data Types Computer Languages A computer language is a language that is used to communicate with a machine. Like all languages, computer languages have syntax (form) and semantics

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

APPENDIX A : KEYWORDS... 2 APPENDIX B : OPERATORS... 3 APPENDIX C : OPERATOR PRECEDENCE... 4 APPENDIX D : ESCAPE SEQUENCES... 5

APPENDIX A : KEYWORDS... 2 APPENDIX B : OPERATORS... 3 APPENDIX C : OPERATOR PRECEDENCE... 4 APPENDIX D : ESCAPE SEQUENCES... 5 APPENDIX A : KEYWORDS... 2 APPENDIX B : OPERATORS... 3 APPENDIX C : OPERATOR PRECEDENCE... 4 APPENDIX D : ESCAPE SEQUENCES... 5 APPENDIX E : ASCII CHARACTER SET... 6 APPENDIX F : USING THE GCC COMPILER

More information

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

COMP322 - Introduction to C++ Lecture 02 - Basics of C++ COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.

More information

Course "Data Processing" Name: Master-1: Nuclear Energy Session /2018 Examen - Part A Page 1

Course Data Processing Name: Master-1: Nuclear Energy Session /2018 Examen - Part A Page 1 Examen - Part A Page 1 1. mydir directory contains three files: filea.txt fileb.txt filec.txt. How many files will be in the directory after performing the following operations: $ ls filea.txt fileb.txt

More information

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable Basic C++ Overview C++ is a version of the older C programming language. This is a language that is used for a wide variety of applications and which has a mature base of compilers and libraries. C++ is

More information

Dr. Md. Humayun Kabir CSE Department, BUET

Dr. Md. Humayun Kabir CSE Department, BUET C++ Dr. Md. Humayun Kabir CSE Department, BUET History of C++ Invented by Bjarne Stroustrup at Bell Lab in 1979 Initially known as C with Classes Classes and Basic Inheritance The name was changed to C++

More information

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in: CS 215 Fundamentals of Programming II C++ Programming Style Guideline Most of a programmer's efforts are aimed at the development of correct and efficient programs. But the readability of programs is also

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

UEE1302 (1102) F10: Introduction to Computers and Programming

UEE1302 (1102) F10: Introduction to Computers and Programming Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1302 (1102) F10: Introduction to Computers and Programming Programming Lecture 00 Programming by Example Introduction to C++ Origins,

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

Lecture 7. Log into Linux New documents posted to course webpage

Lecture 7. Log into Linux New documents posted to course webpage Lecture 7 Log into Linux New documents posted to course webpage Coding style guideline; part of project grade is following this Homework 4, due on Monday; this is a written assignment Project 1, due next

More information

C++ for Python Programmers

C++ for Python Programmers C++ for Python Programmers Adapted from a document by Rich Enbody & Bill Punch of Michigan State University Purpose of this document This document is a brief introduction to C++ for Python programmers

More information

CSE 100: STREAM I/O, BITWISE OPERATIONS, BIT STREAM I/O

CSE 100: STREAM I/O, BITWISE OPERATIONS, BIT STREAM I/O CSE 100: STREAM I/O, BITWISE OPERATIONS, BIT STREAM I/O PA2: encoding/decoding ENCODING: 1.Scan text file to compute frequencies 2.Build Huffman Tree 3.Find code for every symbol (letter) 4.Create new

More information

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program

More information

Programming. C++ Basics

Programming. C++ Basics Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

More information

We will exclusively use streams for input and output of data. Intro Programming in C++

We will exclusively use streams for input and output of data. Intro Programming in C++ C++ Input/Output: Streams The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams: 1 istream

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

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words. , ean, arithmetic s s on acters Comp Sci 1570 Introduction to C++ Outline s s on acters 1 2 3 4 s s on acters Outline s s on acters 1 2 3 4 s s on acters ASCII s s on acters ASCII s s on acters Type: acter

More information

Exercise Session 2 Systems Programming and Computer Architecture

Exercise Session 2 Systems Programming and Computer Architecture Systems Group Department of Computer Science ETH Zürich Exercise Session 2 Systems Programming and Computer Architecture Herbstsemester 216 Agenda Linux vs. Windows Working with SVN Exercise 1: bitcount()

More information

G52CPP C++ Programming Lecture 17

G52CPP C++ Programming Lecture 17 G52CPP C++ Programming Lecture 17 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Exceptions How to throw (return) different error values as exceptions And catch the exceptions

More information